In a generated piece of c code I found something like this (edited):
#include <stdio.h>
int main() {
(void) (
{
int i = 1;
int y = 2;
printf("%d %d\n", i,y);
}
);
return 0;
}
I believe I have never seen the construct (void) ( { CODE } )
before, nor am I able to figure out what the purpose might be.
So, what does this construct do?
({ })
is a gcc
extension called a statement expression.
http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
A statement expression yields a value and the (void)
cast is probably here to remove the compiler warning or to make explicit that the value of the statement expression is not used.
Now (void) ({ })
is the same as a simple compound statement {}
and there is no point of using it.
One application of ({ })
is the ability to replace expressions with code blocks. In this way very complex macros can be embedded in to expressions.
#define myfunc() { } // can be a typical way to automatize coding. e.g.
myfunc(x,y,z);
myfunc(y,x,z);
myfunc(x,z,y); // would work to eg. unroll a loop
int a = myfunc()*123; // but this wouldn't work
Instead
#define myfunc(a,b,c) ({printf(a#b#c);})
int a= myfunc(a,b,c) * 3; // would be legal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With