Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of "(void) ( { CODE } )" in c?

Tags:

c

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?

like image 914
René Nyffenegger Avatar asked Nov 03 '12 15:11

René Nyffenegger


2 Answers

({ }) 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.

like image 196
ouah Avatar answered Nov 07 '22 15:11

ouah


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
like image 2
Aki Suihkonen Avatar answered Nov 07 '22 15:11

Aki Suihkonen