2

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 */ }
iBug
  • 35,554
  • 7
  • 89
  • 134

1 Answers1

2

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)) { 
Déjà vu
  • 28,223
  • 6
  • 72
  • 100