Home > Backend Development > C++ > NULL vs. 0 in C : Which Should I Use for Null Pointers?

NULL vs. 0 in C : Which Should I Use for Null Pointers?

Patricia Arquette
Release: 2024-12-25 11:05:18
Original
520 people have browsed it

NULL vs. 0 in C  : Which Should I Use for Null Pointers?

The Dilemma of Null Pointers: NULL vs. 0

In the tapestry of C coding practices, a debate has emerged regarding the usage of NULL versus 0 (zero) for null pointers. The origins of this discussion lie in the early days of C , when NULL was defined as (void*)0. This constraint limited its assignment to void pointers, rendering it somewhat impractical. Consequently, developers adopted the convention of using 0 as a null pointer.

Preferences have persisted despite the evolution of C . Some programmers, like the author, favor 0 due to its intuitive use as a null value and its compatibility with truth value testing (if (p && !q)). Conversely, others advocate for NULL based on aesthetics.

To address this ongoing question, let's consider the perspective of Bjarne Stroustrup, the creator of C . According to Stroustrup's C Style and Technique FAQ, NULL is effectively synonymous with 0 in C , making it a matter of personal preference. He suggests using 0 to avoid macros and emphasizes that pre-standard NULL definitions sometimes led to unexpected behavior.

In C 11, the nullptr keyword was introduced to explicitly define the null pointer value. However, Stroustrup recommends focusing on code functionality rather than dwelling on nuances.

Ultimately, the choice between NULL and 0 remains a matter of personal preference. Both approaches have their merits, and neither is inherently superior. It's important to ensure consistency within a coding team or project, but there is no objective reason to definitively prefer one option over the other.

The above is the detailed content of NULL vs. 0 in C : Which Should I Use for Null Pointers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template