Is there anything wrong with writing a reference declaration and assignment in one statement. I have tried it using gcc and it seems to work.
int x = 10;
cout << "x = " << x << "\n";
int &y = x = 11;
cout << "x = " << x << "\n";
cout << "y = " << y << "\n";
gives me the expected output
x = 10
x = 11
y = 11
Is this expected to work on most compilers or will there be a portability issue?
In C++, there is an assignment operator, which can be used (at least in
principle) in any expression. Note that in:
The first
=is not an operator; it is part of the syntax of the datadefinition. What follows this
=is an expression, which must resultin an lvalue of type
int. Sincexis anint,x = 11has typeint. And the result of the built-in assignment operator is an lvalue,referring to the object which was the target of the assignment, so
you’ve met the necessary conditions.
Of course, that doesn’t mean that it’s good code.