Reputation:
Are both null and NULL constants the exact same thing in C/C++?
I've noticed as I write my code in Visual Studio that null and NULL don't get the same syntax highlighting, and the compile outcome is not the same as having null instead of NULL in some sections of the code.
Upvotes: 2
Views: 1875
Reputation: 36401
C standard says :
6.3.2.3/3 Pointers
An integer constant expression with the value 0, or such expression cast to type
void *
, is called a null pointer constant.
stddef.h
then contains the NULL
-define to that value.
C++ (another language, roughly related to C, certainly not in the way people usually think) used NULL
in its very early versions (don't use it!). But in pre-C++11 releases, the constant 0
was defined as the way to represent pointers to nothing. Alas, this has some serious drawbacks and then C++11 defined the nullptr
constant. Note that nullptr
is a keyword.
C++ standard says:
2.14.17/1 Pointer literals
The pointer literal is the keyword
nullptr
. It is a prvalue of typestd::nullptr_t
. [ Note:std::nullptr_t
is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.]3.9.1/10 Fundamental types
A value of type
std::nullptr_t
is a null pointer constant. Such values participate in the pointer and the pointer to member conversions.sizeof(std::nullptr_t)
shall be equal tosizeof(void*)
.
About NULL
in C++ standard says:
18.2/3 Types
The macro
NULL
is an implementation-defined C++ null pointer constant.
Upvotes: 2
Reputation: 154
C language has a NULL
but there is no null
. NULL
is used to
indicate the macro defined in and when discussing pointers.
use null
when discussing the null
character. null
character refers to '\0'
.
With that semantics out of the way, if you are asking for the difference
between (x == '\0')
and (x == NULL)
it would depend on what x
is.
Use (x == '\0')
if x
is a char
or int
and (x == NULL)
if x
is
a pointer.
For everything else you'd have to consider whether the
comparison is valid and how things will be converted or promoted.
Upvotes: 0
Reputation: 234715
They might be, they might not be.
Both C and C++ define NULL
, but in slightly different ways.
null
is not part of either standard; it is neither a keyword nor a reserved word, so you can use it as a variable name, class name &c..
The preferred way of denoting pointer null-ness in C++ is nullptr
which has type especially designed for pointer nullness.
Upvotes: 15