What is a reference variable in C++?

后端 未结 12 2124
孤城傲影
孤城傲影 2020-11-22 08:41

What would be a brief definition of a reference variable in C++?

12条回答
  •  长发绾君心
    2020-11-22 09:36

    A reference variable and a pointer variable are the exact same thing to the machine (the compiler will generate the same machine code).

    The most obvious advantages of using a reference variable over a pointer variable in my knowledge:

    1. Easy to understand (no address, de-reference all kinds of headache things)
    2. Saves you a tiny bit of typing, adn thus probably less error-prone.

    In the code below, the left side is using a reference variable, and the right side is using a pointer variable. They are the same thing to the machine, but you see the using reference variable saves you a little bit of typing.

    Reference variable           Pointer variable
    int a = 1;         ~~~~~~    int a = 1;
    int &b = a;        ~~~~~~    int *b = &a;
    b = 2;             ~~~~~~    *b = 2;
    cout << a << '\n'  ~~~~~~    cout << a << '\n'
    ==============================================
    2                  ~~~~~~    2
    

提交回复
热议问题