views:

98

answers:

3

i know what this means

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

but i dont understand well this one

#undef M 

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

+9  A: 

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
Dean Harding
This is a good explanation of what #undef does. But I would say that the most common usage of #undef is in conjunction with simple definitions like "#define DEBUG" and not macro definitions as shown in the question/example. And remember that these are preprocessor definitions and not processed by the compiler.
rotti2
@rotti2: yes, that's a good point. Though I also use `#undef` to undefine those annoying `min` and `max` macros that are in windows.h :-)
Dean Harding
@rotti2: Another use for undef is to replace the definition of a macro. That is, you do `#ifdef A` followed by `#undef A`, `#define A [...]`, then `#endif`.I think if you skip the `#undef A` line the compiler will issue a warning if you `#define A` and A is already defined.
utnapistim
+2  A: 

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.

TJB
A: 

#define and #undef are preprocessor directives.

E.g. #define M(X) 2*(X)

M(1);

#undef M

M(2)

Because are preprocessor directives before compilation the preprocessor will simply replace after the #define M(X) 2*(X) in that source file.

M(1) with 2 * 1

if preprocessor finds #undef M it will not replace anymore

M(2) with 2 * 2 because M is destroyed when #undef M is found.

#undef is ussualy used if want to give another definition for an existing macro

Manu