Home >Backend Development >C++ >NULL vs. 0 in C : Which is the Better Null Pointer?
Pointers in C : NULL vs. 0
In the annals of C programming, the debate rages on: Should you use NULL or 0 (zero) for null pointers? While some programmers hold fast to the tradition of using 0, others swear by NULL. But which approach is truly superior?
Originally, NULL was unusable in C due to its definition as (void*)0. However, with the advent of C 11, the game changed. Now, NULL is explicitly defined as 0, rendering it functionally identical to its numerical counterpart.
Advocates of 0 argue that it's a more logical choice for testing truth values. As the provided code snippet demonstrates, zero naturally fits into logical comparisons using operators like if (p && !q). Using NULL, on the other hand, requires explicit comparisons against NULL unless you assume NULL equals 0 anyway, which defeats the purpose of naming it.
Bjarne Stroustrup, the creator of C , has weighed in on this matter, stating that the choice between NULL and 0 is largely aesthetic. However, he favors 0 due to his preference for avoiding macros and the potential misinterpretations associated with NULL.
Ultimately, the decision between NULL and 0 is a matter of personal preference. Both approaches have their merits, so choose the one that aligns best with your coding style. However, it's worth noting that C 11 introduced the keyword nullptr specifically for this purpose, so it's worth considering its use for clarity and consistency.
The above is the detailed content of NULL vs. 0 in C : Which is the Better Null Pointer?. For more information, please follow other related articles on the PHP Chinese website!