Home >Backend Development >C++ >C Pointers: NULL, 0, or nullptr – Which Should I Use?
Pointers in C : NULL vs. 0
In the early stages of C , the usage of NULL as a null pointer was restricted to void pointers, making it less practical. As a result, programmers adopted the convention of using 0 (zero) to represent null pointers.
Despite the introduction of NULL as a named representation of 0, the debate over which to use persists. Some programmers argue for 0, citing the ability to test pointers as truth values using logical operators (e.g., if (p && !q) do_something()). They maintain that using NULL would require explicit comparisons against NULL or relying on the assumption that NULL is equal to zero.
Others advocate for NULL, echoing Bjarne Stroustrup's view that it's merely an aesthetic difference since NULL is defined as 0 in C . Stroustrup also highlights the potential for confusion when NULL is mistakenly treated as distinct from 0 or non-integer.
While either approach can be debated, Stroustrup urges against excessive concern over minor details. In the era of RAII and exceptions, null pointers are less frequently employed, but their occasional necessity remains.
For those who prefer a named representation, C 11 introduced nullptr as the designated keyword for null pointers. This recommendation serves to differentiate null pointers from other integer values and eliminates the potential for confusion. Ultimately, the choice between NULL and 0 or nullptr comes down to personal preference, as there is no objective superiority between the two approaches.
The above is the detailed content of C Pointers: NULL, 0, or nullptr – Which Should I Use?. For more information, please follow other related articles on the PHP Chinese website!