Skip to content
Related Articles

Related Articles

Improve Article

Uninitialized primitive data types in C/C++

  • Difficulty Level : Medium
  • Last Updated : 04 Sep, 2018
Geek Week

What do you think happens when you use an uninitialized primitive data type?
Well you may assume that the compiler should assign your primitive type variable with meaningful values like 0 for int, 0.0 for float. What about char data type?

Let’s find the answer to that by running the code in the IDE.

#include <iostream>
using namespace std;
int main()
    // The following primitive data type variables will not
    // be initialized with any default values
    char ch;
    float f;
    int i;
    double d;
    long l;
    cout << ch << endl;
    cout << f << endl;
    cout << i << endl;
    cout << d << endl;
    cout << l << endl;
    return 0;

Output in GFGs IDE:


Output in Codechef IDE:


Output on my machine:


Why C/C++ compiler does not initialize variables with default values?

“One of the things that has kept C++ viable is the zero-overhead rule: What you don’t use, you don’t pay for.” -Stroustrup.

The overhead of initializing a stack variable is costly as it hampers the speed of execution, therefore these variables can contain indeterminate values. It is considered a best practice to initialize a primitive data type variable before using it in code.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :