Differences among several ways of writing conditions with pointers
I am wondering if anyone can please summarize the differences among the following ways of writing a conditional statement involving a pointer:
if(p)
if(p != 0)
if(p != NULL)
I am often confused at the following situations (there must be more, please supplement with yours) when to use which:
static char *p1;
char *p2 = new char();
const char *p3 = "hello"; /*then I repeatedly do p开发者_如何学C3++*/
char *p4 = 0;
char *p5 = NULL;
Edit
Also, I'd like to know, for char *p
, do we have while(*p)
or while(*p!=0)
, possibly equivalent to while(p)
or while(p!=0)
or while(p!=NULL)
or while(*p!='\0')
(or any other?) after some p++
inside the while loop?
if(p)
In this context p
is converted to bool
which is effectively the same as p != 0
.
if(p!=0)
This is the explicit way to check for a null pointer, is the same as the previous one.
if(p != NULL)
The difference with this one is that NULL
is a macro; in C is defined as (void*)0
while in C++ is defined as 0
. Again, its the same check than the first two expressions.
Basically, they all do the same thing (with the exception of the NULL
macro not being defined or being redefined to something else). I tend to use p != 0
because its the same as p
but its stated explicitly. The version using NULL
requires including stddef
or cstddef
which is usually not a problem.
In C++11 there is a new way to check for null pointers: nullptr
which is a new keyword. It would be the ideal choice when available, since it states clearly that p
is a pointer:
if( p != nullptr )
These are all ways of checking if p
is not 0
; they do the same thing:
if(p) // Short and simple.
if(p != 0) // Easier to understand.
if(p != NULL) // POINTERS ONLY.
In C++11, you can use this 'safer' way to check if the pointer is NULL
:
if(p != nullptr)
When you want to make a 'dynamically allocated' array of char
s, you do:
char *p2 = new char[4];
strcpy(p2, "abc");
// Don't forget to delete!
delete[] p2;
A better alternative is to use the safer C++:
std::array<char, 256> p2 = {'b', 'b', 'c', 0};
p2[0] = 'a'; // "abc"
Or:
std::string p2 = "bbc";
p2 = "abc";
p2[0] = 'c'; // "cbc"
This sets p3
to the string "hello"
:
const char *p3 = "hello";
This increases the location p3
points to in memory:
// *p3 = 'h';
p3++;
// *p3 = 'e';
p3++;
// *p3 = 'l';
p3++;
// *p3 = 'l';
To understand why you do:
char *p4 = 0;
char *p5 = NULL;
Check out this question: Setting variable to NULL after free
I wouldn't really ever use static char*
s in C++, but here's a stupid example:
void sc(char *first = NULL)
{
static char *p = NULL;
if(p == NULL)
p = &first;
// p will never change (even when sc() ends) unless you set it to NULL again:
// p = NULL;
}
char initial_value;
sc(&initial_value);
sc();
sc();
// ...
精彩评论