Search code examples
cif-statementparentheses

What does this extra pair of parentheses do?


While looking into a piece of code, I saw this line:

if ((b = a)) { /* statements */ }

Reading the context, I know its intention is like this:

b = a;
if (b != 0) { /* statements */ }

I know the two lines above can be simplified into the first code block, but why are the two pair of parentheses? Wouldn't that seem redundant? I think this is totally OK:

if (b = a) { /* statements */ }

Solution

  • Usually one do that to avoid the warning from the compiler, that the assignment is to be (then) evaluated as a condition (in case the developer missed an = in ==)

    warning: suggest parentheses around assignment used as truth value

    Something more indicative,

    int c = !!(b = a); // condition
    
    if (!!(b = a)) {