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?
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
}
}
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;
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;
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