Applying the increment to the ternary operator in C

I thought that the ternary operator returns either a value on the left side or the right side : depending on the condition. Why is this next piece of code printing 1?

 #include <stdio.h> int main(int argc, char const *argv[]) { int c = 0; (c?c:0)++; printf("%i", c); return 0; } 
+4
source share
3 answers

You will have a compiler error, or possibly a language extension, since this is not valid C. To use the ++ operator, an lvalue is required, and (c?c:0) not an lvalue.

+13
source

I just ran into some kind of weirdness related to this. It seems that the result of the triple conditional expression can be considered as an lvalue in gcc 3.3.2, but not in gcc 4.6 (I have no other versions ready for hand to narrow it further). In fact, it is not possible to compile gcc 3.3.2 using gcc 4.6 precisely because gcc 4.6 sorts a lot about what constitutes lvalue.

Another example is from gcc 3.3.2 source that does not compile with gcc 4.6:

 char *x = ...; *((void**)x)++ = ...; 

gcc 4.6 can process the cast result as an lvalue and increment it, but gcc 4.6 will not.

I also do not have the relevant standards to find out about this, is it something that has changed in the official standard or just something that gcc allowed at a certain stage.

Note also that C ++ allows the ternary operator to return an lvalue, although you still cannot increment 0. So this is valid C ++, but not valid C:

 int c = 0, d = 0; (c?c:d)++; 
0
source

Just because you do

 (c?c:0)++; 

If you don't let “++” happen, you get what you want.

 #include <stdio.h> int main(int argc, char const *argv[]) { int c = 0; /* (c?c:0)++; */ printf("%i \n", (c?c:0)++ ); return 0; } 

:

 $ gcc -o ternary ternary.c $ ./ternary 0 

gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)

-2
source

All Articles