5

I.e. are these legal statements:

int x = 1, y = z = 2;
int& a = x, b = c = y;

with the intended result that a is an alias for x, whileb and c are aliases for y?

I ask simply because I read here

Declaring a variable as a reference rather than a normal variable simply entails appending an ampersand to the type name

which lead me to hesitate whether it was legal to create multiple reference variables by placing & before the variable name.

mchen
  • 9,808
  • 17
  • 72
  • 125
  • 3
    is your compiler broken? – Mitch Wheat May 05 '13 at 03:27
  • Hint: it's like pointers. – chris May 05 '13 at 03:28
  • No - just wanted to check in caution before writing the code. – mchen May 05 '13 at 03:28
  • 1
    @MiloChen, A simple test on the compiler would tell you. All you have to do is change x, y, and z, and then print a, b, and c. – chris May 05 '13 at 03:29
  • Note that `int& a, b;` declares `a`, a reference-to-int, and `b`, an int. The `&` must be specified for each declared variable, just like `*` or `[]`. – cdhowie May 05 '13 at 03:29
  • 7
    don't write code like this please. – yngccc May 05 '13 at 03:29
  • 2
    Pray Tell - Why are you writing such crap code? Job security perhaps?! – Ed Heal May 05 '13 at 03:31
  • I simply got confused by the tutorial at http://www.cprogramming.com/tutorial/references.html, which emphasizes appending an ampersand to the **type** name with the example given as `int& foo = ....;`. – mchen May 05 '13 at 03:38
  • 1
    @MiloChen, Perhaps it's time for a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – chris May 05 '13 at 03:39
  • @MiloChen This is exactly why I advocate for the opposite placement: `int &foo = ...;`. But the real answer is "don't declare more than one variable at a time." – cdhowie May 05 '13 at 03:41

2 Answers2

12
int x = 1, y = z = 2;--incorrect
int& a = x, b = c = y;--incorrect

The statements should be like this:

int x = 1, y =2,z = 2;
int&q=x,&b=y,&c=y;

All assignment and initialization statements in c++ should be of the following type:

lvalue=rvalue;

here lvalue must always be a variable to which a temporary value/another variable is assigned. rvalue can be another variable or an expression that evaluates to a temporary variable like (4+5).

thunderbird
  • 2,715
  • 5
  • 27
  • 51
4

You need to append a & on the left of each reference (like you would need a * when you declare a pointer).

selalerer
  • 3,766
  • 2
  • 23
  • 33