'Decrementing and incrementing a variable with an if condition produces unexpected result in C language
I'm running this code from the command prompt. The output of this code is 0 but I was expecting it to output 1. Can you explain how this code is actually compiled and runs?
#include <stdio.h>
int main() {
int x;
x = 1;
if (--x && ++x) {
printf("Great");
}
printf("%d\n", x);
return 0;
}
Solution 1:[1]
--x decrements the value of x before using the value of the variable. So you start with x=1, then do an if clause
if (--x
which decrements x and then inspects the value. The value is now 0. You haven't put any other boolean test in there, in C if (0)
equates to false
. So it doesn't execute the second part of the conditional (which would incremenet x), it simply skips the 'if' clause and goes to printf and return 0.
If you change this to something like:
if (--x >= 0 && ++x >= 0)
Or:
if (x-- && x++)
Because x-- uses the variable before decrementing it, so the if
will test x when its value is 1, before decrementing it. Then it'll do what you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | halfer |