Const usage in C + + (3)--Reference parameter problem

Source: Internet
Author: User

The reference parameter usage for C + + functions is probably this:

void swap (int &a,int &b) {    int temp = A;    A = b;    b = temp;}

A simple function for exchanging two int numbers, when calling the function, such as

int i = 3;int j = 4;swap (i,j);

The result is i=4,j=3. Because the reference parameter is actually an alias of an argument, manipulating the reference parameter is the same as passing a pointer. If you use the normal int parameter, you will not get this effect.


If you use the const modifier parameter, such as const int &a, to indicate that the parameter cannot be changed, there is a problem that requires special attention.

int incr (int &val) {    return ++val;} int main () {short    v1 = 0;    const INT v2 =;    int v3 = incr (v1); V1 is a short type, and the formal parameter is int type    v3 = incr (v2);     V2 is a const, and the formal parameter is non-const    return 0;}


As I've described earlier, a const variable cannot be assigned to a const variable, so a const-type V2 cannot be passed to a non-const parameter.

A non-const reference parameter can only be associated with a non-const object of exactly the same type, so the short type V1 cannot be passed to an int parameter. Therefore, a formal parameter that does not modify the corresponding argument should be defined as a const reference. If such a parameter is defined as a non-const reference, the use of the function is limited.

Const usage in C + + (3)--Reference parameter problem

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.