简体   繁体   中英

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?

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;

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.

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 .

你可以实现你想要的: x = y = z = 0.50;

你可以像这样在一行中做到这一点:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM