Why n++==--n
always equal to 1? The following code gives output as 1.
#include <stdio.h>
int main(){
int n=10;
printf("%d\n",n++==--n);
}
The output is always 1, no matter what n
is.
Why n++==--n
always equal to 1? The following code gives output as 1.
#include <stdio.h>
int main(){
int n=10;
printf("%d\n",n++==--n);
}
The output is always 1, no matter what n
is.
If compiled with gcc -Wall
, the following warning is obtained:
a.c: In function ‘main’:
a.c:4:20: warning: operation on ‘n’ may be undefined [-Wsequence-point]
printf("%d\n",n++==--n);
~^~
There is a good explanation in the gcc
manpage about this, the section which begins:
-Wsequence-point
Warn about code that may have undefined semantics because of violations of sequence
point rules in the C and C++ standards.
[...etc...]
which is well worth a read, because it discusses the issues in more detail, although the basic point is that the result depends on the ordering of operations whose ordering is not fully constrained by the standards, and is therefore undefined.
I probably can't reproduce it in full here without also adding a lot of licence information in order to comply with the GFDL. There is a copy at https://gcc.gnu.org/onlinedocs/gcc-3.3.6/gcc/Warning-Options.html
(Take-home message: always compile your code with compiler warnings switched on, but especially if you are seeing possibly unexpected behaviour.)