The title of this node is valid, legal, C (or C++). Some have said that it is undefined by ANSI, ISO, and the like. This is not true. What is true is that C = C++ (a completely different expression) is not defined. But put this code into any C program and feed it to gcc, and it will compile. Give it any flags you like: I suggest -ansi -pedantic -Wall, for starters. You will get no warnings. If you put this into an if clause, the body of the if (and not the else) will always be executed.
The reason for this should be clear: the compiler compares the left hand, C, with the right hand, C++. C++ uses the postincrement operator, so it evaluates to C, and then increments C after the expression is evaluated. So the comparison is always true. In fact, if you compile with -O (and -S, if you don't want to read object code), you can see that the comparison has been completely dropped, as has the else clause (if you included one).
Of course, it is not true that the language C is the same as C++, and as has been noted elsewhere, there are several incompatibilities between them. So feel free to express yourself by including C != C++ in your programs; the compiler will just ignore you.
For those too lazy to write it themselves, I have included a program using this in an if clause. Compiled with -ansi -pedantic -Wall -O -S, you see two things:
- No warnings.
- The assembly code does not contain the string "No" anywhere. It has been optimized away.
#include <stdio.h>
int main(void)
{
int c = 0;
/* Make sure the optimizer isn't cheating by relying on c=0 */
scanf("%d", &c);
if (c == c++)
printf("Yes");
else
printf("No");
return 0;
}
EDIT:
It has been pointed out to me that this is false. The behavior actually is undefined. Thanks to jrn for this catch. Stay tuned to find out why it's undefined.