+ 2

Ok here i write a simple program for adding two values.

#include <iostream> using namespace std; int a=5; int b=8; int sum=a+b; int main() { cout<<"The sum is="<<sum; return 0; } i don't declare the variables inside the main function. still then i get the desired output. does that implies that it is not necessary to declare the variables inside the main fuction.or in short Is it necessary to declare the variables inside the main function. thanks

19th Jul 2017, 6:47 AM
stephen haokip
stephen haokip - avatar
2 Answers
+ 1
you declare global variables (which declare outside the function)so that all the function in your program can reach and use , or else you can just declare a local one which you declare inside the function and it will only can be used by that particular function
19th Jul 2017, 8:20 AM
Janie Lee
Janie Lee - avatar
- 1
Do you know scope of variable ? Variables declared outside any block are globals. That means they are reacheable everywhere in the code, after there declarations. So yes it is possible. BUT IT'S NOT A GOOD IDEA : It's recommended to declare the variable very cloth to the first moment it's used. Exemples: int a; int main (){ a=6;//correct } int main(){ int a; a=6;//almost perfect ;) } int main(){ { // In C++ you can create a block whenever you want using {} int a; } a=7;//error. 'a' exists from its declaration to the end of the block where it was declared... } The last exemple is more complicated, ask if you don't understand
19th Jul 2017, 7:16 AM
Jojo