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)
.
- C++11 introduced
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.