2

I've just been shown a very neat C trick:

int myInt = ( { int x=42; x; } ); // sets myInt to 42

This is very useful for writing macros. But what exactly is going on here? Could someone pick this line apart and isolate/identify the mechanisms?

P i
  • 29,020
  • 36
  • 159
  • 267
  • 5
    GNU extension, statement-expression. **It's not portable.** – Daniel Fischer Jun 16 '13 at 12:48
  • Why is it useful for macros? – JeffRSon Jun 16 '13 at 12:49
  • 2
    @JeffRSon: it allows you to put loops and other control statements into "expressions" resulting from macro expansion. It gives you the same thing as inline functions, without the kind of namespace/scope controls that functions offer and enforce. (My rule of thumb here is, use inline functions rather than GnuC statement-expressions whenever possible.) – torek Jun 16 '13 at 12:56
  • @torek: thanks +1 , i didnt knew it could be used like that !! – Nitin4873 Jun 16 '13 at 16:04

1 Answers1

0

It's the same as int myInt = 42;. Just initializing with an expression whose value comes from x which has been initialized by 42.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51