Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NULL in C++? [duplicate]

Tags:

c++

null

Possible Duplicate:
Do you use NULL or 0 (zero) for pointers in C++?

Is it a good idea to use NULL in C++ or just the value 0?

Is there a special circumstance using NULL in C code calling from C++? Like SDL?

like image 864
Jookia Avatar asked Aug 26 '10 17:08

Jookia


People also ask

What does == null mean in C?

Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

What happens if you strcpy null?

The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string. No length checking is performed.

How do you copy a null to a string?

strncopy copies the null terminator as long as you specify the correct length of the string that is being copied. strncpy will also copy the null terminator, if there's space. For the expected effect, you'd want something like memcpy(s1, s2, strlen(s2)) . strncpy(s1,s2,strlen(s2)) should also not copy the 0-terminator.

How do you use null in C?

In practice, NULL is a constant equivalent to 0 , or "\0" . This is why you can set a string to NULL using: char *a_string = '\0'; Download my free C Handbook!


1 Answers

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

like image 99
Tarantula Avatar answered Sep 22 '22 22:09

Tarantula