13

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?

unwind
  • 378,987
  • 63
  • 458
  • 590
Ashish Rawat
  • 3,245
  • 2
  • 25
  • 33

2 Answers2

17

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.

gsamaras
  • 69,751
  • 39
  • 173
  • 279
Anirudh Ramanathan
  • 45,145
  • 22
  • 127
  • 184
  • 2
    NULL has the size of a pointer (typically 32 or even 64 bits). NUL has the size of a character (typically 8 bits in C, and sometimes 16 in other languages that support 16-bit Unicode). They can't be used interchangeably. If you're using a 0 in a string, it's NUL. If you're using a 0 in a pointer, it's NULL. Only NULL has a macro in C. In C, all literal strings get a NUL 0 byte appended at the end automatically by the compiler, so there's no need for a macro. – nonrectangular Sep 30 '15 at 17:55
  • @nonrectangular "NULL has the size of a pointer" --> maybe. It might have the size of an `int`. The _type_ of `NULL` is not specified. – chux - Reinstate Monica Jan 01 '17 at 21:26
14

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.

unwind
  • 378,987
  • 63
  • 458
  • 590
  • 3
    Even stronger, avoid using `NULL` for characters, because if your code ever becomes C++11, being able to search-and-replace `NULL` with `nullptr` gives you extra type safety. And every use of `NULL` for the integer constant zero that isn't a pointer will make this harder. – Yakk - Adam Nevraumont Mar 18 '13 at 15:19
  • 1
    the reason for nullptr is that its a void * pointer. NULL in C is not. So the 'some reason' is for type safety – pm100 Jun 19 '17 at 16:06