Hi
Does this code satisfy ANSI C syntax ?
void function(void)
{
int a = 2;
a = ({int c; c = a + 2;}); /* <<-- here !! */
printf("a=%d\n", a);
}
Thanks !
tsuyoshi
I think this is invalid for ANSI C, since ANSI C require each
declaration for variable to be in place before all execution
statement.
But however it will work on, compiled by gcc. But if you try
Microsoft's compiler, it won't work, since they have no interest to
implement the new C99 syntax.
The compiler did not give any warning or error it is because the
compiler suppose such syntax, namely, declaration after the execution
code. For instance
for( int i = 0; i < count; i++ )
the code above is not valid for ANSI C but valid for C99, and gcc
think it is OK.
in ANSI C it should be;
int i;
/* some other code perhaps */
for( i = 0; i < count; i++ )
The reason that your code give the result a = 4 is below:
when C find the assignment "=", it require its right operand to return
a value, and assign this value to the left operand.
In this case it find a block, "{...}". It will execute this block of
code and get the value by this execution. Every assignment will return
a value, which is the value it assigned to its left operand. So after
c = a + 2;
been executed, the first "=" get the value returned by "c = a + 2",
namely, 4. This is what you got.
To illustrate this more clearly, see below:
#include <dirent.h>
/* some codes */
DIR *dp;
if( ( d = opendir( argv[ 1 ])) == NULL )
/* other codes */
This will work though the left operand of "==" is an assignment
statement, not a variable or constant. Because
d = opendir( argv[ 1 ])
will return the value of
opendir( argv[ 1 ] )