Uninitialized primitive data types in C/C++

CC++Server Side ProgrammingProgramming

One of the most frequent question is what will be the value of some uninitialized primitive data values in C or C++? Well the answer will be different in different systems. We can assume the compiler will assign 0 into the variables. It can be done for integer as 0, for float 0.0, but what will be for character type data?

Example

#include <iostream>
using namespace std;
main() {
   char a;
   float b;
   int c;
   double d;
   long e;
   cout << a << "\n";
   cout << b << "\n";
   cout << c << "\n";
   cout << d << "\n";
   cout << e << "\n";
}

Output (On Windows Compiler)

1.4013e-045
0
2.91499e-322
0

Output (On Linux Compiler)

0
0
0
0

So, now the question comes, why C or C++ is not assigning some default value for variables? The answer is, the overhead of initializing stack variables is costly. It hampers the speed of execution also. So these variables may contain some intermediate value. So we need to initialize the primitive datatype values before using it.

raja
Published on 26-Apr-2019 12:50:43
Advertisements