rkachach
rkachach

Reputation: 17345

comparing the address of string with NULL

I came across something similar to this reviewing some code:

std::string mystring;
if (&mystring != NULL)
{
   DoSomething();  
}

Does this make any sense? could somebody explain some use case of this?

Upvotes: 0

Views: 220

Answers (3)

MikeMB
MikeMB

Reputation: 21156

No, in the code you showed, the comparison doesn't make any sense whatsoever and will always evaluate to true.

My wild guess:

  • mystring was originally a char* (maybe c-code).
  • Someone refactored it blindly to a std::string.
  • That lead to a compiler error and to silence it, the address operator was put in place.

EDIT: It might be worth to have a closer look at DoSomething, to determine, if the code is supposed to check for an empty string instead. But if the code passes all tests, I'd say, it's more likely that it can simply be removed.

Upvotes: 3

eerorika
eerorika

Reputation: 238351

Does this make any sense?

No, it does not make sense. The address of a variable is never equal to NULL.

could somebody explain some use case of this?

Perhaps it is an attempt to sanity check a broken compiler, or some UB within the code. In either case, I doubt it would be very effective.

With the assumption that the compiler is not broken, I see no use for the condition. And that is an assumption that most of us get to / must make every day.


As H. Guijt suggested, I also find it plausible that the check is a re factoring artefact that happened when a tired programmer changed the code to use std::string instead of a pointer, and then "fixed" the test to be syntactically correct, even though it is now meaningless.

Upvotes: 2

Husita
Husita

Reputation: 24

No sense.

std::string mystring; is allocated in the stack.

so you're verifying the address of this variable allocated in the stack is not null. That's not possible unless there's a Weird memory corruption.

https://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Basic_architecture_of_a_stack

Upvotes: -1

Related Questions