Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use #ifndef with macro argument?

Tags:

c++

c

c++11

macros

I have a simple code in header.h-

#define SWAP(a, b)  {a ^= b; b ^= a; a ^= b;} 

This header.h is included in a code.c file, but my requirement is- I want SWAP to be checked first like-

#ifndef SWAP(a, b)
#define SWAP(a, b)  {a ^= b; b ^= a; a ^= b;}
#endif

Is this correct or I don't have to provide the argument to the first line?

like image 799
A. Gupta Avatar asked Dec 01 '22 10:12

A. Gupta


1 Answers

You want to code

#ifndef SWAP
#define SWAP(a, b)  {a ^= b; b ^= a; a ^= b;}
#endif

The #ifndef is just looking into the preprocessor's symbol table (for the presence or absence of some given preprocessor symbol). It does not care about the arguments of your SWAP macro.

Of course in genuine C++11 you should prefer the standard std::swap function. It is typesafe, more readable, and safer (think about SWAP(t[i++],i) as a misbehaving example).

like image 168
Basile Starynkevitch Avatar answered Dec 04 '22 21:12

Basile Starynkevitch