About Me

My photo
I look only to the good qualities of people. .. Not being faultless myself, I won't presume to probe into the faults of others.

Thursday, August 12, 2010

Difference between null and zero

The term 'null' is overloaded in C. JosAH described what is meant by a 'null pointer'. Here are a few other usages of the word in C. For all I know, there could be additional usages in C++.

1. The null character (used at the end of a null-terminated string).
The null character is of type char and it must be encoded as the value 0. Notice that this must be true of whatever character encoding system (ASCII, EBCDIC, etc.) is used by any and all C compiler implementations. The proper way to indicate this value in your software is as character constant '\0'. The null character always compares to a 'false' value in a boolean context (such as in an if-expression). Notice that in the ASCII character encoding, the name of the null character is "NUL".

2. The null wide character (used at the end of a wide string).
The null wide character is of type wchar_t and it must be encoded as the value 0. The null wide character always compares to a 'false' value in a boolean context (such as in an if-expression).

3. The null statement.
The null statement consists simply of a semicolon. The null statement is used primarily in two situations. In the first case, a null body is used as the body of an iterative statement (while, do, or for). The second case is where a label is desired just before the right brace that terminates a compound statement. A label cannot simply precede the right brace, but must always be attached to a statement.

Regarding null pointers, pedantically portable C code is careful to treat data pointers differently than function pointers. The C Standard permits an implementation to use different size pointers for each. The NULL macro has data pointer type void*. Therefore, you should not compare function pointer variables to NULL; instead compare against a literal "0". Unfortunately, Standard C doesn't provide a generic null function pointer macro. My personal practice is to provide macro FNULL (Function pointer NULL) with value "0".

No comments:

Post a Comment