Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize multiple variables in C++ to the same value?

Tags:

c++

c++11

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?

like image 742
Alan S. Avatar asked Mar 08 '16 20:03

Alan S.


3 Answers

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
    }
}
like image 101
Kerrek SB Avatar answered Oct 26 '22 22:10

Kerrek SB


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;
like image 39
Rabbid76 Avatar answered Oct 26 '22 21:10

Rabbid76


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;
like image 44
FrankS101 Avatar answered Oct 26 '22 22:10

FrankS101