dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Beginner
Feb 24, 2000

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Assign Zero or NULL to a Pointer

Question:
To initialize a pointer after deleting it, should I assign a NULL to it or zero? Are they the same in C++? I know strictly speaking, I should assign NULLs to deleted pointers. But the app I work with uses zeros instead. I wonder if I need to change them.

Answer:
C and C++ define NULL differently. A typical definition of NULL in C++ looks like this:

 #define NULL 0 
Whereas in C, NULL is usually defined like this:
 #define NULL  ((void*)0) 
Why is this? Pointers in C++ are strongly-typed, unlike pointers in C. Thus, void* cannot be implicitly converted to any other pointer type without a cast operation. If C++ retained C's convention, a C++ statement such as:
  char * p = NULL; 
would be expanded into:
  /*error: incompatible pointer types*/
  char * p = (void*) 0; 
For this reason, the C++ standard requires that NULL be defined either as 0 or as 0L. In other words, NULL is just an alias for the literal zero. Therefore, you may use zero as a pointer initializer directly. There's no need to replace 0 with NULL.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date