Something that will bite you in the hiney is C’s reliance on single vs. doubled-up characters for certain related but not congruent functionality.

It’s not if, but when you’ll lose hours or even days hunting an “inexplicable” bug…

if (a = 42) {
  // Do the thing

You know this by now, but for posterior: a single equals (=) is an assignment, double equals (==) is a comparison. In vs. out. The code above is assigning where it should be comparing…and because the result is non-zero, always evaluates as true.

This happens all the time, and will happen forever.

Complexifying matters, and on theme with this guide’s focus, seasoned coders sometimes economize on space by intentionally putting an assignment inside an if (or while, etc.) statement…

if ((value = func())) {
  // Do the thing

This calls func(), assigns the returned result to value, then does the thing if the result was non-zero. This is actually normal and valid C syntax, and at most it’s optional but recommended to have double parenthesis (as above) as if to tell others, “I meant to do that.”

Assignment sometimes gets paired up with another, different character (or two) to perform an operation on a variable in one compact step, for example…

x += 3;  // Add 3 to x, assign result back to x; equiv. to x = x + 3
x -= 3;  // Subtract 3 from x, assign back to x; equiv to x = x - 3
x *= 3;  // Multiply x by 3, assign result back to x; equiv x = x * 3
x /= 3;  // Divide x by 3, and so forth...
x %= 3;  // x modulo 3, "
x &= 3;  // Bitwise AND of x and 3, "
x |= 3;  // Bitwise OR of x and 3, "
x ^= 3;  // Bitwise XOR of x and 3, "
x <<= 3; // Shift x left 3 bits, assign result back to x
x >>= 3; // Shift x right 3 bits, assign result back to x

But a few of these, syntactically similar, are actually comparisons…

if (x != 3) // If x does not equal 3...
if (x <= 3) // If x is less than or equal to 3...
if (x >= 3) // If x is greater than or equal to 3...

Of these, the bitwise shifts vs greater/less-than comparisons are most likely to cause misunderstandings.

This guide was first published on Aug 10, 2022. It was last updated on Sep 06, 2016.

This page (Compare vs Assign) was last updated on Aug 08, 2022.

Text editor powered by tinymce.