-4

Is this piece of code any good to check if a pointer or variable hold a nullptr value?

if(strcmp(variable/pointer, nullptr) == 0){
    Do something cool
}

I'm trying to work on some code and I want to know the best way to check if there is a nullptr value present. Thanks.

Mekanic
  • 101
  • 10

3 Answers3

1

I think what you want is

if (!pointer || !variable) { 
    // do something cool
}

!pointer is essentially the same thing as pointer == nullptr and is considered by some to be better style. See Can I use if (pointer) instead of if (pointer != NULL)?

strcmp is meant to be for C string comparisons. https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

Curious
  • 20,072
  • 7
  • 51
  • 128
1

You cannot use strcmp to check whether a variable is equal to nullptr. From strcmp documentation:

Parameters
lhs, rhs - pointers to the null-terminated byte strings to compare

Not only do the input arguments to strcmp need to point to byte strings, they must point to null-terminated byte strings.

Besides, you are making things may more complex than they need to be. You can just use:

if ( variable != nullptr )
{
    // Do something
}
else
{
    // Do something else
}
R Sahu
  • 200,579
  • 13
  • 144
  • 260
0

strcmp() has undefined behaviour if either argument is a null pointer. Therefore it is necessary to check for null before calling strcmp().

For example, to only call strcmp() if both intended arguments are not null

 if (first && second && !strcmp(first, second))
 {
      // first and second are both non-null, and contain matching strings
 }

or (more verbosely, C++11 and later)

 if (first != nullptr && second != nullptr && strcmp(first, second) == 0)
 {
      // first and second are both non-null, and contain matching strings
 }

In C++, you'd be better off using the std::string type, rather than messing around with arrays of char, string termination, and functions like strcmp().

Peter
  • 34,264
  • 4
  • 28
  • 68