Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment works as a condition

Consider the following code,

int i;
while (i = 0)
    printf("Hello");

Now generally speaking, i = 0 is an assignment and not a condition for while to check.

But the GCC compiler lets it go with a warning and even evaluates it correctly (does not execute the printf statement).

Why? I usually would do with parenthesis for the truth value, but my juniors feel that I am wrong and there isn't any real reason for the parenthesis in this!

Zeroing down on the actual doubt, please consider the following test case:

int callme() {
    return 0;
}

int main(int argc, char *argv[]) {
    int c;
    while (c = callme()) {
        printf("Calling...\n");
    }
    return 0;
}
like image 908
Nathan Avatar asked Dec 10 '25 06:12

Nathan


1 Answers

The expression i = 0 does 2 things:

  • Has the side effect of storing 0 in i
  • Yields the value 0

I usually would do with parenthesis for the truth value but my juniors feel that i am wrong and there is no real reason for the parenthesis in this

It's usually a hint to the compiler meaning "I actually want this, I didn't forget a =, shut up".


For your specific case there's no reason to write if (i = 0): you already know what if (0) does. But it's pretty useful when used as:

if ((i = some_function()))
    ...
like image 152
cnicutar Avatar answered Dec 11 '25 21:12

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!