Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL == pointer [duplicate]

Tags:

c++

c++11

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

like image 707
minicaptain Avatar asked Jul 21 '13 12:07

minicaptain


2 Answers

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:

  1. if(ptr == NULL) is the same with if(!ptr).
  2. 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.

like image 192
Yu Hao Avatar answered Sep 20 '22 07:09

Yu Hao


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.

like image 33
Ed Heal Avatar answered Sep 20 '22 07:09

Ed Heal