+ 2

For variables to be printed is it compulsory to initialize the variables first? In c++

20th Jul 2019, 4:08 AM
Merlyn J
5 Answers
+ 9
In C++ there are different kind of variables like auto, extern, static , register etc. When you declare a variable it's auto by default. And auto variables by default stores a garbage value in them.
20th Jul 2019, 5:23 AM
Manoj
Manoj - avatar
+ 5
Yes. Unless you print the expressions themselves directly. For example, print(1+1) puts 1+1 cout<<1+1<<endl; document.write(1+1); System.out.println(1+1); Just for a few languages.
20th Jul 2019, 4:11 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
Sometimes it may work for some languages without initialising because the compiler may auto initialise the variable to 0 but that is bad practice. https://code.sololearn.com/cyQiLyn1huXT/?ref=app
20th Jul 2019, 4:29 AM
Sonic
Sonic - avatar
+ 1
So in c++ do we have to compulsorily intialise the variables?
20th Jul 2019, 4:37 AM
Merlyn J
+ 1
Yes it is because if you don't initialise the variable then it will print some random value or garbage value. Let say:- Int main(){ int x; cout<<x; return 0; } In this example when you compile and run it ,it will not show any error but as we didn't initialise variable so it will print some random value or we can say garbage value
20th Jul 2019, 5:09 AM
Puneet