NULL
and nullptr
has little to do with null-terminated strings. Both NULL
and nullptr
are used to denote a pointer which points to nothing, ie. null.
The null-termination of c-style strings is still (and has always) been denoted by a CharT
having the integral value 0
; or as it's most often written when talking, through a char-literal; '\0'
.
Remember that character types are nothing more than integral types with some special meaning.
Comparing a char
to an int
(which is the type of literal 0
) is allowed, it's also allowed to assign the value 0
to a char
, as stated: a character type is an integral type.. and integral types hold integral values.
Why this confusion?
Back in the days when we didn't have nullptr
, instead we had the macro NULL
to denote that a certain pointer didn't have anything to point towards. The value of NULL
is, and was, implementation-specific but the behaviour was well-defined; it shall not compare equal to any pointer value that is actually pointing to something.
As a result of how the behaviour of NULL
was described plenty of compilers used #define NULL 0
, or similar construct, resulting in a "feature" where one could easily compare NULL
to any integral type (including char
) to see if it's relation to the value zero.
With the previously stated in mind you'd often stumbled upon code such as the below, where the for-condition would be equivalent of having *ptr != 0
.
char const * str = "hello world";
for (char const * ptr = str; *ptr != NULL; ++ptr) {
...
}
Lesson learned: Just because something works doesn't mean that it is correct...