I am just getting into learing C++, and have a question about variable declaration location in code, and the importance of why they need to be declared in a certain spot. This is just play code for learning purposes.
#include <iostream>
int x = 0;
int a = 0;
int b = 0;
int function2()
{
usingnamespace std;
cout << "I like to add!" << endl;
cout << "And want 2 more single digit numbers" << endl;
cin >> a;
cin >> b;
x = x + a + b;
cout << x << endl;
return 0;
}
int function1()
{
usingnamespace std;
cout << "Are you having fun yet?" << endl;
cout << "Gimme 2 more please" << endl;
cin >> a;
cin >> b;
x = x + a + b;
cout << x << endl;
function2();
return 0;
}
int main()
{
usingnamespace std; // I make comments
cout << "hello world!" << endl;
cout << "Enter 2 Single Digit Numbers" << endl;
cin >> a;
cin >> b;
x = a + b;
cout << x << endl;
function1();
cout << "Press any enter to continue....." << endl;
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
With this code I get the undeclared variables error during compiling. My question is why?
I realize I do not know all there is to know about C++, but this is a concept I cant seem to locate an answer for. For some reason I see the need, somewhere down the road, to carry values for variables into other functions. Since the program starts in MAIN, why does the code break during compiling giving the undeclared variable error?
Am i just being picky? it makes more sence to declare the variable in the first function to make use of it and then have the ability to carry that value over into called functions.
The program may start in main but the compiler doesn't. The compiler starts at the top.
Anyway, inside any function, the following variables exist:
1) Variables created inside that function
2) Global variables
3) Variables passed into that function
So look at this:
1 2 3
int function2()
{
int f2x = f1x;
f1x does not exist inside this function. The fact that some other function somewhere creates a variable with this name is completely irrelevant.