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.
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.
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.
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.
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.
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).
You need to append a & on the left of each reference (like you would need a * when you declare a pointer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With