Preferring NULL or Zero for Pointers in C
In C , the topic of using NULL or zero (0) for pointers has been a matter of debate for some time. While the early days of C restricted NULL to void* pointers, it has since been redefined as 0. However, some individuals continue to favor zero.
Those who prefer zero argue that it is inherently more logical and convenient. They contend that since zero can be used for truth value comparisons, it makes more sense than NULL, which requires an explicit comparison. Additionally, they question the value of giving a name (NULL) to an existing value.
On the other hand, those who favor NULL cite the guidance provided by Bjarne Stroustrup, the creator of C . According to Stroustrup, the definition of NULL in C is 0, making it essentially an aesthetic preference. He recommends avoiding macros, including NULL, and instead using 0.
Stroustrup also notes that in C 11, the nullptr keyword was introduced as the official name for the null pointer. This provides a clear and consistent way to represent null pointers in code.
Ultimately, the choice between zero and NULL may come down to personal preference. However, it is important to consider the opinions of the community and the guidance provided by the language's creator. In cases where clarity and consistency are paramount, using nullptr is recommended.
The above is the detailed content of NULL or Zero for Pointers in C : Which Should You Prefer?. For more information, please follow other related articles on the PHP Chinese website!