Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of #undef in C++

I know what this means

#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B)) // CHAR_BIT=bits/byte

but I don't understand well this one:

#undef M 

after this what happens? M is cleared or deleted or?

like image 452
dato datuashvili Avatar asked Jul 08 '10 07:07

dato datuashvili


2 Answers

After the #undef, it's as if the #define M... line never existed.

int a = M(123); // error, M is undefined

#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B))

int b = M(123); // no error, M is defined

#undef M

int c = M(123); // error, M is undefined
like image 121
Dean Harding Avatar answered Oct 22 '22 14:10

Dean Harding


Here is the MSDN article about it: http://msdn.microsoft.com/en-us/library/ts4w8783(VS.80).aspx

My understanding is that it removes the definition of M so that it may be used to define something else.

E.G.

#define M(X) 2*(X)
int a = M(2); 
ASSERT(a == 4);
#undefine M
#define M(X) 3*(X)
int b = M(2);
ASSERT(b == 6);

It seems like a confusing thing to use but may come up in practice if you need to work with someone else's macros.

like image 27
TJB Avatar answered Oct 22 '22 12:10

TJB