Zero Initialization


C++ by default does not initialize automatic variables. For the fundamental types (such as int, double, or pointer types and “Plain Old Data” (POD)), there is no default constructor that initializes them with some default value. Consequently, uninitialized auto variables and aggregates have undefined value.



int x;             // x has undefined value


The auto variables can be zero-initialized by instantiating them with syntax of the default constructor.



int x = int();     // x has ‘0’ value


For the same reason it is recommended to use zero-initialization syntax in template code like as below:



template <typename T>
void MyFunction()
{
    T x = T();    // x is zero (or false) if ‘T’ is a built-in type
}

Zero Initialization Zero Initialization Reviewed by Sourabh Soni on Monday, February 01, 2010 Rating: 5

No comments

Author Details

Image Link [https://3.bp.blogspot.com/-zo21XIdyPqc/VuTrFfUyPhI/AAAAAAAAAO8/EEWTN73XHUA7aTIjuxuBSN-WGaGkNUymA/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]