Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are NUL and NULL interchangeable in C? [duplicate]

Tags:

c++

c

Just read pointer on C book by Kenneth Reek. It says that a NUL byte is one whose bits are all 0, written like this '\0' and NULL has a value 0 which refers to a pointer whose value is zero.

Both are integers and have the same value, so they could be used interchangeably.

and this code also:

char const *keyword[] = { "do", "for", "if", "register", 
                              "return", "switch", "while", NULL };

In this code, the NULL lets functions that search the table detect the end of the table. So, can we interchange NULL and NUL macros?

like image 681
Ashish Rawat Avatar asked Mar 18 '13 14:03

Ashish Rawat


2 Answers

NUL is the notation for an ASCII character code 0.

NULL is a macro defined in stddef for the null pointer.

So, no, they are not to be used interchangeably.

like image 97
Anirudh Ramanathan Avatar answered Sep 18 '22 07:09

Anirudh Ramanathan


There is no standardized NUL macro, at least not in C.

Also, NULL has the advantage over a plain 0 literal that it signals to the reader that "hey, we're dealing with a pointer" which might be considered an advantage.

In C++, the idiom was for a long while to just write 0, but then they seem to have reversed that and introduced a new literal, nullptr for some reason(s).

In C, I recommend writing NULL for pointers and '\0' for characters.

like image 32
unwind Avatar answered Sep 21 '22 07:09

unwind