Open In App

Zero Initialization in C++

Setting the initial value of an object to zero is called zero initialization.

Syntax

static T object;

Tt = {} ;

T {} ;

char array [n] = " ";

Zero initialization is performed in the following situations:- 

  1. Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.
  2. Zero is initialized as part of the value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors.
  3. When a character array is initialized with a string literal which is very short, the remainder of the array is zero-initialized.

The effects of zero-initialization are:  

Key Points:  

Below program illustrates zero initialization in C++:  




// C++ code to demonstrate zero initialization
 
#include <iostream>
#include <string>
 
struct foo {
    int x, y, z;
};
 
double f[3]; // zero-initialized to three 0.0's
 
int* p; // zero-initialized to null pointer value
 
// zero-initialized to indeterminate value
// then default-initialized to ""
std::string s;
 
int main(int argc, char* argv[])
{
    foo x = foo();
     
    std::cout << x.x << x.y << x.z << '\n';
     
    return 0;
}

Output
000

In this example logic is same but program is quite different than above example. Below is another method of Zero Initialization in C++.




#include <iostream>
#include <string>
 
using namespace std;
 
struct S {
    int g, q, r;
};
double f[3];    //zero-initialised to three 0.0's
int* p;         // zero initialized to null pointer value.
string u;      
 
int main(int argc, char*[])
{
    delete p;      // safe to delete a null pointer
    static int n = argc;   //zero-initialized to 0then copy-initialized to argc
    cout << "n=" << n << '\n';
 
    S g = S();      //the effect is same as: S g{}; or Sg={};
    cout << "g={" << g.g <<" " << g.q <<" " << g.r
         << "} \n";
 
        return 0;
}

Output
n=1
g={0 0 0} 

Article Tags :