On understanding how printf("%d\n", ( { int n; scanf("%d", &n); n*n; } )); works in C

block, c, printf

Solution

This code is using a "GNU C" feature called statement-expressions, whereby a parentheses-enclosed compound statement can be used as an expression, whose type and value match the result of the last statement in the compound statement. This is not syntactically valid C, but a GCC feature (also adopted by some other compilers) that was added presumably because it was deemed important for writing macros which do not evaluate their arguments more than once.

You should be aware of what it is and what it does in case you encounter it in code you have to read, but I would avoid using it yourself. It's confusing, unnecessary, and non-standard. The same thing can almost always be achieved portably with static inline functions.

Problem

I came across this program via a quora answer ``` #include<stdio.h> int main() { printf("%d\n", ( { int n; scanf("%d", &n); n*n; } )); return 0; } ``` I was wondering how does this work and if this conforms the standard?

Original source

Related problems