Note: This article refers to the http://blog.csdn.net/mylinx/article/details/6873253 and books "Conquering the C-pointer" ([Day] front bridge and Messiah).
The values of NULL, ' + ' and 0 are the same, all 0, but they do not behave the same way:
1. null: null pointer, but not the same in C and C + +. It can be seen in the library file String.h vs 2013 If defined.
1/* Define null pointer value */2 #ifndef NULL3 #ifdef __CPLUSPLUS4 #define NULL #else/ * __cplusplus */6 #def INE null ((void *) 0) 7 #endif/ * __cplusplus */8 #endif/ * NULL */
As you can see, in C, null represents a pointer to 0, whereas in C + +, NULL is directly the same as 0. But one thing to note is that in C, "when constant 0 is in the context that should be used as a pointer, it is used as a null pointer" ("Conquer the C Pointer"). For example, the following pointer definition and initialization is no problem (i.e. no warning or error):
int * p = 0; /* C language */
But what if it is defined as follows?
int * p = 3; /* C language */
Obviously, there is something wrong with this. This sentence can be compiled through, but in vs 2013 there is a warning: "Warning C4047:" Initialization ":" Int * "and" int "The indirect level is different".
I tried again. In the case of C + +, VS 2013 has a direct error: "The value of type ' int ' cannot be used to initialize an ' int * ' type entity".
So, in order to prevent confusion, in C + +, when you assign a pointer to a null pointer, you should assign it to null instead of 0.
2. ' + ': ' \ S ' is a "null character" constant, which represents the end of a string with an ASCII value of 0. Note that it is not the same as the space ' (ASCII value is 32) and ' 0 ' (ASCII code value is 48).
In the conquest of the C-pointer, the author also mentions a wrong way of writing: using NULL to end a string. For example, the program below is problematic:
Char str[4] = {' 1 ', ' 2 ', ' 3 ', NULL}; /* C language */
In vs 2013, the warning: "Warning C4047:" Initialization ":" char "differs from" void * "in the indirect level. In C + +, there is no problem with this sentence.
It is also worth noting that the following programs are not problematic in C/s + +:
Char str[4] = {' 1 ', ' 2 ', ' 3 ', 0}; /C + + language */
However, in order to prevent confusion, when you want to add an end flag to a string, you should use ' + ' instead of NULL or 0.
In summary, when we want to set a pointer to null, should be NULL, when we want to give a string to add the end flag, we should use ' "".
The difference between null, ' + ', and 0 in the C + + language