In C++,we usually check a pointer whether is null or not, I just know we should use
if(NULL == ptr)
instead of:
if(ptr == NULL)
I want to know why?
In additiol, if we want to initialized a ptr to null,should we use ptr = NULL
or ptr = 0
? yes I know in C++, we usually use ptr = nullptr
, I want to know why shall we do like this just want to unify the code ? thanks
It's a coding style (named Yoda Conditions) to avoid writing =
instead of ==
in an if-statement, it's valid to use assignment =
in an if-statement, but it's usually not what you want.
Personally, I prefer not to use like this because it's hard to read and modern compilers will warn you when you use =
in an if-statement.
Also note that:
if(ptr == NULL)
is the same with if(!ptr)
.nullptr
to replace using NULL
. So to initialize a null pointer, it's preferred to use ptr = nullptr
About why use nullptr
over NULL
:
Before C++11, NULL
is usually implemented internally as #define NULL 0
, but the problem is, 0
is also the integer zero. It may cause trouble in some situations. For example:
void func(int n);
void func(char *s);
func(NULL); //call which function?
Though the auther implies that NULL
is a pointer type, but the compiler just know to call func(0)
. So the first version will be called.
Using func(nullptr)
, the compiler will know it's a pointer and call the second version.
Using yoda equality it prevents certain mistakes such as using a single =
or where the compiler tries to determine an integer from a smart pointer.
It has been known
I spent two days tracking down that error as they think yoda is a bad idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With