jeudi 25 novembre 2021

Strange behaviour of if in C++

At my work I tried to use this construction:

if (repl && (repl = replaced.count(*l))) {
    // repl isn't used here 
    ...
}

and in my mind it should work the same way as

bool newRepl = replaced.count(*l);
if (repl && newRepl) {
    // repl isn't used here 
    ...
}
repl = newRepl;

because expressions in && evaluate from left to right, but unexpectedly it's not.
Is it a not specified construction in C++ or I don't correctly understand how it should work?

Example of code with a problem:

std::set<int> set{3, 4, 6};
bool repl = false;
for (size_t i = 3; i < 7; ++i) {
    if (repl && (repl = set.count(i))) {
        std::cout << "strangeif" << std::endl;
    }
}

output:

std::set<int> set{3, 4, 6};
bool repl = false;
for (size_t i = 3; i < 7; ++i) {
    bool newRepl = set.count(i);
    if (repl && newRepl) {
        std::cout << "strangeif" << std::endl;
    }
    repl = newRepl;
}

output: strangeif

Aucun commentaire:

Enregistrer un commentaire