Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Style: When using c function in c++, should I check for NULL or nullptr?

Tags:

c++

In a C++ program, if I want to use a c function that will return NULL for any error, should I check for nullptr or NULL?

int * ptr = someCfunction();
if (ptr == nullptr)
    return false;

or:

int * ptr = someCfunction();
if (ptr == NULL)
    return false;

Which one is better in terms of style?

like image 361
Elaine Chen Avatar asked Nov 29 '18 05:11

Elaine Chen


People also ask

Should I use null or nullptr?

nullptr is a keyword that represents zero as an address (its type is considered a pointer-type), while NULL is the value zero as an int . If you're writing something where you're referring to the zero address, rather than the value zero, you should use nullptr .

Can nullptr be used in C?

At a very high level, we can think of NULL as a null pointer which is used in C for various purposes.

What is the difference between null and nullptr?

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. Unlike NULL, it is not implicitly convertible or comparable to integral types.

IS null equivalent to nullptr?

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 an integer literal that evaluates to zero.


1 Answers

From the cppreference on nullptr, you can see that there is implicit conversion from nullptr to NULL. So you can do either but (as good practice) better use nullptr from C++11 onwards.

The keyword nullptr denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

like image 54
P.W Avatar answered Oct 20 '22 00:10

P.W