Reputation: 313
Would this kind of variable assignment work?
double a = 2.0,
x, y, z = 0.5;
Would the second line of code work properly and initialize x, y, z
each to 0.5?
Upvotes: 26
Views: 50632
Reputation: 26
You could do that in a single line like this:
double x = 0.5, y = 0.5, z = 0.5;
Upvotes: 0
Reputation: 210890
No, only z
would be initialized .You have to write it like this:
double x = 0.50, y = x, z = x;
But you can write an assignment like this:
double x, y, z;
x = y = z = 0.50;
Upvotes: 19
Reputation: 83
You can achieve what you want doing this: x = y = z = 0.50;
Upvotes: 2
Reputation: 966
The second line of code:
double x;
x = 50.1;
actually has a return value. Usually, it is not caught, or used, but it is there. So x = 50.1
returns the value 50.1.
This implies that you could do:
double x,y,z;
x = y = z = 50.1;
And the value will make its way up the chain where x = y
returns and the value isn't caught again. After that line is executed, x, y and z will all have the value 50.1.
Upvotes: 4
Reputation: 11237
If you want to assign to all three variables, write
x = y = z = 0.5;
which is equivalent to
x = (y = (z = 0.5));
The code that you present only assigns to z
.
Upvotes: 2
Reputation: 2135
Simply No. Only z will be initialized.
If you try to print them afterwards
std::cout << a << " " << x << " " << y << " " << z;
you will get this kind of warning from the compiler:
warning: 'x' is used uninitialized in this function
For the sake of clarity I would use the second option that Rabbid76 suggested:
double x, y, z;
x = y = z = 0.50;
Upvotes: 5
Reputation: 476970
Your code leaves x
and y
uninitialized. However, a slight rearrangement can save you from repeating an initial value:
double a = 2.0, x = 0.50, y = x, z = x;
Variables that are declared earlier in a declaration are in scope of later declarations.
This is sometimes particularly useful when evaluating one initializer may have a non-trivial runtime cost. For example, in the following nested loop where m
is a multimap:
for (auto it = m.begin(), kt = it, e = m.end(); it != e; it = kt)
{ // ^^^^^^^^^^^^^^^^^^^^^^^
// handle partition
for (; kt != e && kt->first == it->first; ++kt)
{
// ... handle equal-range
}
}
Upvotes: 19