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

Recommended Answers

All 2 Replies

>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.

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.