Const modifier participates in real parameters

Source: Internet
Author: User

It is best to regard const as a part of the parameter, and keep the form parameters consistent with the real parameters. The following example shows when an error occurs when the real parameters involved in the form participate in the const modification is inconsistent, when and why.

# Include <iostream> using namespace STD; void string_copy (char *) {cout <"string_copy invoked";} int main () {const char * pc_str = "this is a test"; string_copy (pc_str );}

Note the aboveCode, The form parameter is char *, and the real parameter is of the const char * type. This method is not compiled. The parameter is char *, so the content to which it points can be changed inside the function. However, the real parameter we pass to it is const char *, meaning that the content to which the real parameter points does not want to be changed, the compiler detects this conflict and reports an error. Next, let's exchange the writing method. The real parameter is changed to char * and the form parameter is changed to const char *. Is there a problem?

# Include <iostream> using namespace STD; void string_copy (const char *) {cout <"string_copy invoked";} int main () {char * pc_str = "this is a test"; string_copy (pc_str );}
Practice has proved that it can be compiled and passed, because the content pointed to by the parameter cannot be changed. Both the const char * and char * parameters can meet the conditions, so no error is reported, however, a warning is reported, which is not recommended by the compiler. This is not easy to understand. Conclusion: real parameters cannot have more restrictions than the actual parameters.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.