Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null pointer in C++

Tags:

c++

everyone, I have some question about C++, what do You actually prefer to use

int* var = 0;

if(!var)...//1)
or
if(var == 0)..//2)

what are the pros and cons? thanks in advance

like image 864
rookie Avatar asked Dec 31 '25 08:12

rookie


2 Answers

I prefer if (!var), because then you cannot accidentally assign to var, and you do not have to pick between 0 and NULL.

like image 192
fredoverflow Avatar answered Jan 02 '26 00:01

fredoverflow


I've always been taught to use if (!var), and it seems that all the idiomatic C(++) I've ever read follows this. This has a few nice semantics:

  • There's no accidental assignment
  • You're testing the existence of something (ie. if it's NULL). Hence, you can read the statement as "If var does not exist" or "If var is not set"
  • Maps closely to what you'd idiomatically write if var was a boolean (bools aren't available in C, but people still mimic their use)
  • Similar to the previous point, it maps closely to predicate function calls, ie. if (!isEmpty(nodeptr)) { .. }
like image 33
Andrew Song Avatar answered Jan 02 '26 01:01

Andrew Song



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!