References to C + + variables

Source: Internet
Author: User

Yao Brothers yesterday when asked to quote, there was a little bit of an ignorant. Usually used in the reference time is the function of the parameter passing.

A reference is an alias for a variable, and the operation of the reference is exactly the same as for a variable, but it is important to note that the reference does not have a new memory space and therefore does not account for the inner deposit element. When declaring a reference, it must be initialized at the same time.

To simply understand the reference, write the following code:

    intA =Ten; intb = -; Std::cout<<"a"<< &a <<Std::endl; Std::cout<<"b"<< &b <<Std::endl; Std::cout<<"________________________"<<Std::endl; int&c=A; Std::cout<<"a"<< &a <<Std::endl; Std::cout<<"b"<< &b <<Std::endl; Std::cout<<"C"<< &c <<Std::endl; Std::cout<<"________________________"<<Std::endl; C=b; Std::cout<<"a"<< &a <<Std::endl; Std::cout<<"b"<< &b <<Std::endl; Std::cout<<"C"<< &c <<Std::endl; Std::cout<<"________________________"<< Std::endl;

The result of the code operation is as follows:

However, in the previous debugs, when the code went to "C=B;" , you see that the value of A,b,c is 20. The small head is a bit chaotic, and once thought that the variable C is also a reference to the variables A and B. It is known that after the reference is initialized, it is no longer possible to alias the reference as another variable. At one point it was c++11 that the rules had been revised, and had specifically checked the official documents of C++11. Almost did not respond to come over. Think carefully, the original "C=B;" Instead of modifying the alias, it is simply a simple shaping assignment that is logically equivalent to "c= 20", and the code above is written to validate the idea. It turns out that the address of the variable C is the same as the variable a address, and does not change its address after "C=B;" is executed.

References to C + + variables

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.