Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare multiple reference variables on the same line in C++?

Tags:

c++

reference

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.

like image 268
mchen Avatar asked May 05 '13 03:05

mchen


People also ask

Can you declare multiple variables in one line in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can you declare a variable more than once?

Declaring multiple variablesYou can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.

Can a variable have multiple declarations justify your answer?

Declaring multiple variables in a single declaration could cause confusion about the types of variables and their initial values. In particular, do not declare any of the following in a single declaration: Variables of different types.

Can we declare multiple variables in a single line in Java?

Like Java, we can declare and assign multiple variables in one line. In this tutorial, we'll addresses approaches to do that: Separating declarations by semicolons. Assigning two variables using a Pair object.


2 Answers

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).

like image 163
thunderbird Avatar answered Oct 16 '22 09:10

thunderbird


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

like image 39
selalerer Avatar answered Oct 16 '22 10:10

selalerer