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;
}
The expression i = 0 does 2 things:
0 in iI 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()))
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With