"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > NULL vs. 0 in C++: Which is the Better Null Pointer?

NULL vs. 0 in C++: Which is the Better Null Pointer?

Posted on 2025-03-22
Browse:206

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3