Actually, you can use a literal 0 anyplace you would use NULL.
Section 6.3.2.3p3 of the C standard states:
An integer constant expression with the value 0, or such an expression cast to type
void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
And section 7.19p3 states:
The macros are:
CopyNULLwhich expands to an implementation-defined null pointer constant
So 0 qualifies as a null pointer constant, as does (void *)0 and NULL. The use of NULL is preferred however as it makes it more evident to the reader that a null pointer is being used and not the integer value 0.
Actually, you can use a literal 0 anyplace you would use NULL.
Section 6.3.2.3p3 of the C standard states:
An integer constant expression with the value 0, or such an expression cast to type
void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
And section 7.19p3 states:
The macros are:
CopyNULLwhich expands to an implementation-defined null pointer constant
So 0 qualifies as a null pointer constant, as does (void *)0 and NULL. The use of NULL is preferred however as it makes it more evident to the reader that a null pointer is being used and not the integer value 0.
NULL is used to make it clear it is a pointer type.
Ideally, the C implementation would define NULL as ((void *) 0) or something equivalent, and programmers would always use NULL when they want a null pointer constant.
If this is done, then, when a programmer has, for example, an int *x and accidentally writes *x = NULL;, then the compiler can recognize that a mistake has been made, because the left side of = has type int, and the right side has type void *, and this is not a proper combination for assignment.
In contrast, if the programmer accidentally writes *x = 0; instead of x = 0;, then the compiler cannot recognize this mistake, because the left side has type int, and the right side has type int, and that is a valid combination.
Thus, when NULL is defined well and is used, mistakes are detected earlier.
In particular answer to your question “Is there a context in which just plain literal 0 would not work exactly the same?”:
- In correct code,
NULLand0may be used interchangeably as null pointer constants. 0will function as an integer (non-pointer) constant, butNULLmight not, depending on how the C implementation defines it.- For the purpose of detecting errors,
NULLand0do not work exactly the same; usingNULLwith a good definition serves to help detect some mistakes that using0does not.
The C standard allows 0 to be used for null pointer constants for historic reasons. However, this is not beneficial except for allowing previously written code to compile in compilers using current C standards. New code should avoid using 0 as a null pointer constant.
What is Null?
What does it mean to do a "null check" in C or C++? - Software Engineering Stack Exchange
C Langauge and Checking For NULL
c - Are there reasons to assign NULL instead of 0 to non-pointer variables? - Software Engineering Stack Exchange
Videos
So I use C# and I often see many devs use null.
What and which kind of situation do you use this variable?
I am reading c# guide on programming book and I am on Clearing memory now and I haven't encountered null yet. Should I be worried?
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).
A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):
void fill_foo(int* foo) {
*foo = 23; // this will crash and burn if foo is NULL
}
A better version:
void fill_foo(int* foo) {
if (!foo) { // this is the NULL check
printf("This is wrong\n");
return;
}
*foo = 23;
}
Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.
The other answers pretty much covered your exact question. A null check is made to be sure that the pointer you received actually points to a valid instance of a type (objects, primitives, etc).
I'm going to add my own piece of advice here, though. Avoid null checks. :) Null checks (and other forms of Defensive Programming) clutter code up, and actually make it more error prone than other error-handling techniques.
My favorite technique when it comes to object pointers is to use the Null Object pattern. That means returning a (pointer - or even better, reference to an) empty array or list instead of null, or returning an empty string ("") instead of null, or even the string "0" (or something equivalent to "nothing" in the context) where you expect it to be parsed to an integer.
As a bonus, here's a little something you might not have known about the null pointer, which was (first formally) implemented by C.A.R. Hoare for the Algol W language in 1965.
I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
I'm new to C and would like to know best practices for NULL checking.
In languages like Javascript I check for null/undefined all the time.
For building a software framework:
-
How much NULL checking is enough in a C program.
-
How about assertions?
-
Can you go too far?
-
What are best practices in C?
like:
typedef void (*freeFuncPtr)(Mechanism*);
void mechFree(Mechanism* d) {
if (d) {
assert(d->class);
assert(d->class->delete);
freeFuncPtr funct = mech->class->delete;
(funct)(d);
free(d);
}
}mechFree is used by "our user" (the developer) so they could accidentally send NULL to this function. However, we (the framework builders) implemented d->class and d->class->delete so assert seems ok.
I know some of this is programming style and context is also really important but some best known C programming practice hints would be really helpful.
Edit: fixed coding bug
The macro NULL is a null-pointer constant and has either an integer type or a pointer type.
Using NULL to assign or initialize a non-pointer variable will lead to question marks from other programmers at the least and it might result in compiler failures.
A line like
int a = NULL;
is not considered good code and it will make the code less readable.
I think @R Sahu's answer reaches the right conclusion, but the supporting evidence it provides (based on a single implementation) is somewhat weak, at best.
This is tagged with both c and c++. The details of how NULL is defined vary between the two, and also varies over time for C++. In all cases, NULL must expand to an "implementation defined null pointer constant". What varies is the definition of "null pointer constant".
In C, a null pointer constant must be an integer literal with the value 0, or the same cast to type "pointer to void"1. An integer with a non-zero value (by itself, or cast to type "pointer to void") is not allowed2. So, 0, 0L and ((void *)0) are all allowed, but something like ((void *)1234) is not.
In C++ 98/03, NULL must also expand to a null pointer constant--but with a somewhat different definition of the term--in particular, casting the integer literal to type "pointer to void" is not allowed in C++ 98/03. This means 0 and 0L are both allowed (and so would '\0' or, if you wanted to be really perverse, (3-(2 + 1)).
In C++ 11, the nullptr_t type and nullptr literal were added to C++, and nullptr is also allowed as a null pointer constant3. NULL is allowed to expand to any null pointer constant, so it could be 0, 0L (etc.) or nullptr, but (again) cannot be any non-zero integer, nor can it have type "pointer to void" (or "pointer to char", etc.)
The intent, however, has always been that NULL only be used to represent a null pointer. Although both C and C++ allow it to be defined as an unadorned 0 (for one example), so it might be possible to assign it to a variable of type int, there's no guarantee that code that does so will even compile (and a fair number of people believe that it shouldn't compile).
Conclusion: you should only ever assign NULL to a pointer. For new code, I'd advise using NULL only in C, and using nullptr in C++. For existing C++ code, I'd convert to using nullptr when any other refactoring is being done on that code, but would not usually modify the code solely to change NULL to nullptr (but code that assigns NULL to any non-pointer type should be corrected immediately, in either C or C++).
1. The wording in the C standard (§6.3.2.3/3) reads:
An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
The italics (which are in the original) mean that this is considered the definition of that term for this standard.
2. Assigning a null pointer constant to a pointer variable may result in a non-zero value being stored into that variable. Although somewhat unusual, this is perfectly allowable. Even if/when that is the case, however, comparing that variable to a null pointer constant (e.g., NULL or 0) must yield true.
Likewise, an implementation is free to define any number of other integer constants that will produce a null pointer when assigned to a pointer variable. This doesn't affect the requirement on how NULL must be defined.
3. Here, the official wording (from [conv.ptr]) reads:
A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t.
Here again, the italics indicate that this is the official definition of the term for that standard.