Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define NULL NULL

Tags:

c++

c

null

macros

#ifndef NULL
#define NULL NULL
#endif

This code compiles in gcc with no warnings/errors. Can someone explain what the preprocessor is doing here?

like image 703
J. Polfer Avatar asked Dec 22 '09 22:12

J. Polfer


3 Answers

Anywhere the compiler sees the text "NULL" it will replace it with the text "NULL". It's like doing a search-and-replace in your code for "NULL" and replacing with "NULL". Not illegal, just weird :)

like image 102
Doug T. Avatar answered Oct 25 '22 06:10

Doug T.


The only possible reason for doing this would be to do it before including header files which themselves do something like

#ifndef NULL
#define NULL (void *)0
#endif

This would then stop the NULL from being defined like that.

like image 23
Artelius Avatar answered Oct 25 '22 04:10

Artelius


It's normal:

#ifndef JON_SKEET
#define JON_SKEET JON_SKEET
#endif

This compiles too. This is because the preprocessor simply does mindless replaces. What it replaces and what it replaces with don't need to be valid identifiers.

Think of it like this: open your editor's Search & Replace window and type in "NULL" in both the Replace and Replace with fields. It won't give any error or warning and it will "work", even though it actually doesn't do anything. The preprocessor does the same thing.

Obviously when you try to use it:

'JON_SKEET' undeclared (first use in this function)
(Each undeclared identifier is reported only once
for each function it appears in.)
like image 40
Thomas Bonini Avatar answered Oct 25 '22 05:10

Thomas Bonini