Hi i always mix up a NULL and '\0' and 0.
Can you write me when to use these things?

9 Years
Discussion Span
Last Post by kv79

>i always mix up a NULL and '\0' and 0.
The short answer is that you use NULL with pointers, '\0' with characters, and 0 with everything else.

The long answer is that '\0' and 0 are identical. In C they're both integers with the value 0. You can use them interchangeably, but it's best to only use '\0' in a character context, because it's a character literal. You can use 0 at any time because it's so multi-functional and that fact is well known. You're less likely to confuse people.

NULL is not interchangeable with '\0' and 0 because it may be cast into a pointer type[1]:

#define NULL ((void*)0)

Therefore you can only safely use NULL in a pointer context because if it casts the expression to void*, you'll get mysterious warnings and errors when using NULL in a non-pointer context.

[1] In other words, the standard doesn't require this. It says that "an integer constant expression with the value 0, or such an expression cast to type void*, is a null pointer constant". So you can use 0 instead of NULL in a pointer context as well. 0 always works. NULL may also be defined just as 0, but you can't be sure of it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.