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.
CPP
#include <iostream>
using namespace std;
int main()
{
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;
}
|
C
#include <stdio.h>
int main( void )
{
char ch;
float f;
int i;
double d;
long l;
printf ( "%c\n" , ch);
printf ( "%f\n" , f);
printf ( "%d\n" , i);
printf ( "%lf\n" , d);
printf ( "%ld\n" , l);
return (0);
}
|
Output in GFGs IDE:
5.88052e-39
0
6.9529e-310
0
Output in Codechef IDE:
0
0
0
0
Output on my machine:
1.4013e-045
0
2.96439e-323
0
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 or garbage values as memory space is provided when we define a data type. It is considered a best practice to initialize a primitive data type variable before using it in code.