Question

I somehow start to try to understand C++ and get confused with "undefined", "unspecified".

References are widely documented, but I didn't find the the answer to my "specific" question.

What about a reference of a value passed by reference?

I have tested this with the following code:

#include <iostream>

int func(int& a)
{
    int b=a;
    ++b;
    std::cout << "[func] b: " << b << std::endl;
    return b;
}

int func2(int& a)
{
    int& b=a;
    ++b;
    std::cout << "[func2] b: " << b << std::endl;
    return b;
}

int main()
{
    int a=1;
    std::cout << "a: " << a << std::endl;
    func(a);
    std::cout << "a after func: " << a << std::endl;
    func2(a);
    std::cout << "a after func2: " << a << std::endl;
    return 0;
}

and got the output:

a: 1
[func] b: 2
a after func: 1
[func2] b: 2
a after func2: 2

It seems to do what I expect, but is this the behavior mandated by the standard?

Was it helpful?

Solution

From the latest public standard draft, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf:

8.5.3 References [dcl.init.ref] 1 A variable declared to be a T& or T&&, that is, “reference to type T” (8.3.2), shall be initialized by an object, or function, of type T or by an object that can be converted into a T. [ Example:

int g(int);  
void f() {   
    int i;   
    int& r = i; // r refers to i  
    r = 1; // the value of i becomes 1 
    int* p = &r; //p points to i 
    int& rr = r; // rr refers to what r refers to, that is, to i
[...]

So while the sentence may leave one uncertain (the part relevant here is probably that a reference "can be converted into a T"), the example (the last line is relevant here) is unambiguous.

OTHER TIPS

yes this is the standard behavior.

When you pass something by refernce - you are actually just assigning one more name to the variable.

Like -

When you call func2(int& a) using func(a) from main you are assigning a new name to variable 'a' defined in main. The main variable 'a' is known by the name 'a' in func2. Basically fun2::a and main::a refer to the same variables.

Also, when you do int & b=a; in func2 you are making a new name for func2::a - >func2::b. Thus the variable remains the same only new names are added.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top