Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using nullptr instead of NULL when mixing C and C++

i have a very simple question...

i am using the SDL API which was written in C. i am using C++. my compiler supports the keyword nullptr, and I've been reading up on it. it seems as if it is better to use rather than using the NULL macro.

when I call SDL_SetVideoMode, I assume it returns NULL on failure, so if i do:

SDL_Surface *test = nullptr;

if ((test = SDL_SetVideoMode(params)) == nullptr)
{
    // to-do code
}

will this accurately check if my optimization on the surface test was successful?

like image 731
john Avatar asked Jan 22 '12 03:01

john


People also ask

Can I use nullptr instead of null?

nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type.

What can I use instead of null in C?

Instead of NULL , they use nullptr , a new keyword introduced in C++11. Like NULL , nullptr implicitly converts to T* for any type T . Unlike NULL , nullptr is not an integer so it cannot call the wrong overload. Unlike NULL , nullptr has its own type, nullptr_t , so the compiler makes correct type deductions.

Is nullptr equal to zero?

nullptr vs NULL NULL is 0(zero) i.e. integer constant zero with C-style typecast to void*, while nullptr is prvalue of type nullptr_t which is integer literal evaluates to zero.

Does nullptr exist in C?

In C, two null pointers of any type are guaranteed to compare equal. The preprocessor macro NULL is defined as an implementation-defined null pointer constant, which in C99 can be portably expressed as ((void *)0) which means that the integer value 0 converted to the type void* (pointer to void).


1 Answers

Yes. nullptr is comparable to and equivalent to a null pointer of any other pointer type.

like image 93
Kyle Jones Avatar answered Sep 19 '22 10:09

Kyle Jones