NULL is often used in the context of pointers, and is defined via macros in multiple standard libraries (such as <iostream>
) to be the integer 0
. '\0'
is the null character, and is 8 bits of zeros. Incidentally, 8 bits of zeros is equivalent to the integer 0
.
In some cases, although it is considered to be horrible style, these two can be interchanged:
int *p='\0'; if (p==NULL) //evaluates to true cout << "equal\n";
Or
char a=NULL; char b='\0'; if (a==b) //evaluates to true cout << "equal again\n";
There are already many similar questions on SO alone; for example, the top answer for this question (What is the difference between NULL, '\0' and 0) says "they are not really the same thing."
Could anyone provide an example that NULL
and \0
cannot be interchanged (preferably an actual application and not a pathological case)?
The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0.
Each array is terminated with '\0' or null character but if we store a '0' inside a string both are not same according to the C language. '0' means 48 according to the ASCII Table whereas '\0' means 0 according to the ASCII table.
Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.
\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).
Could anyone provide an example that NULL and \0 cannot be interchanged?
The difference between NULL
and '\0'
may affect overload resolution.
Example (check it on Coliru):
#include <iostream> // The overloaded function under question can be a constructor or // an overloaded operator, which would make this example less silly void foo(char) { std::cout << "foo(char)" << std::endl; } void foo(int) { std::cout << "foo(int)" << std::endl; } void foo(long) { std::cout << "foo(long)" << std::endl; } void foo(void*) { std::cout << "foo(void*)" << std::endl; } int main() { foo('\0'); // this will definitely call foo(char) foo(NULL); // this, most probably, will not call foo(char) }
Note that the gcc compiler used at Coliru defines NULL
as 0L
, which for this example means that foo(NULL)
resolves to foo(long)
rather than to foo(void*)
. This answer discusses that aspect in detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With