Alan S.
Alan S.

Reputation: 313

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

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

Answers (7)

Gabriel Baril
Gabriel Baril

Reputation: 26

You could do that in a single line like this:

double x = 0.5, y = 0.5, z = 0.5;

Upvotes: 0

Rabbid76
Rabbid76

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

You can achieve what you want doing this: x = y = z = 0.50;

Upvotes: 2

Louis Parkin
Louis Parkin

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

lost_in_the_source
lost_in_the_source

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

FrankS101
FrankS101

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

Kerrek SB
Kerrek SB

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

Related Questions