Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ void cast and operator comma in a #define

Tags:

c++

macros

I found this while reading some source code.

 #define MACRO(x)  if((void) 0, (x)); else some_func();

I don't fully understand the reasons behind that operator comma and the void cast. This has probably something to do with macro protection, I know that (void)0 is used sometimes to protect cascading elses in macros such as in if(...) then foo(); else (void)0.

Any ideas of why operator comma is there?

edit: I'm starting to think this has something to do with the owl (0,0).

like image 568
Giovanni Funchal Avatar asked Oct 12 '10 14:10

Giovanni Funchal


2 Answers

I would guess that the trick is used to prevent the user from declaring variables in the if condition. As you probably know, in C++ it is legal to do this

if (int i = some_func()) {
   // you can use `i` here
}
else  {
   // and you can use `i` here
}

The use of comma operator in that definition will prevent macro usage like

MACRO(int i = some_func());

and force the user to use only expressions as argument.

like image 199
AnT Avatar answered Nov 02 '22 01:11

AnT


The void conversion there is definitely to prevent calling an overloaded operator , since you can't overload with a void parameter. This guarantees that (void)0, has no effect.

Why the comma operator is there? A good question. I really don't know.

like image 36
Yakov Galka Avatar answered Nov 01 '22 23:11

Yakov Galka