kafman
kafman

Reputation: 2860

Assignment in if clause has no effect

Consider the following code (I realize it's bad practice, just curious to see why it happens):

#include <iostream>

int main() {
    bool show = false;
    int output = 3;

    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    output = 0;
    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    return 0;
}

This prints

3
show: 1
0
show: 1

So, apparrently in the 2nd if clause, the assignment of output, which is 0, does not actually happen. If I re-write the code like this:

#include <iostream>

int main() {
    bool show = false;
    int output = 3;

    if (show = output || show)
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    output = 0;
    if (show = output)  // no more || show
        std::cout << output << std::endl;
    std::cout << "show: " << show << std::endl;

    return 0;
}

It outputs, as I would expect:

3
show: 1
show: 0

Can anyone explain what is actually happening here? Why is output not assigned to show in the 2nd if clause of the 1st example? Im using Visual Studio 2017 Toolchain on Windows 10.

Upvotes: 1

Views: 75

Answers (2)

HugoTeixeira
HugoTeixeira

Reputation: 4884

This is related to operator precedence. Your code:

if (show = output || show)

is the same as

if (show = (output || show))

If you change the order, the result changes:

if ((show = output) || show)

With an if-statement like the one above, it prints:

3
show: 1
show: 0

Upvotes: 6

tsp
tsp

Reputation: 333

The assignment does not happen because operator precedence of the || operator is higher than the assignment operator. You assign output || show which is 0 || true which evaluates to true in the second if.

Upvotes: 2

Related Questions