I found the following construct, where a variable is assigned to what seems to be a compound statement, foo
, in a driver. For comparison, bar
yields undefined behaviour be treating the same code as a proper function. It doesn't seem to conform with my understanding of the C language and its preprocessor, so I suspect that it is a GCC extension. What is the logic executed here? (See output here.)
#include <stdio.h>
#define foo(c) ({ int x = c; x; })
int bar(char c) {
int x = c;
x;
}
int main(void) {
int x = foo('0');
int y = bar('A');
printf("%d\n%d\n", x, y);
return 0;
}
Output:
48
0
There are two different things involved here.
Firstly, the so called "statement expression"
({ int x = c; x; })
, which is a GCC extension. This expression in GCC evaluates to the well-defined value ofx
. The value it evaluates to is defined by the last expression inside the({...})
, which isx
in your case. (BTW, the preprocessor has little to do with it. You don't have to involve preprocessor to use statement expressions in GCC.)Secondly, your function
bar
, which is declared to returnint
but lacks a return statement. This has nothing to do with any extensions. This function does not return any defined value. If the calling code attempts to use the value returned bybar
, the behavior is undefined. Thex
expression at the end ofbar
is just a no-op that does not change anything.