Variables must be declared. For instance:
double num1;
Variables should always be initialized with a value, otherwise they will be given junk values, and if there is a coding error you may end up with junk values and not realize where they came from. An example of variable initialization:
double num1 = 0.0;
Variable Scope
Variable scope in C++ is very different than in PHP. In C++, a variable is local to the code block in which it was declared—where a code block is the section between braces, {…}. Example:
int numZero = 3;
int main(){
int numOne = 5;
if(numOne>4) {
int numTwo = 10;
cout << numZero*numOne*numTwo << endl; // Outputs 150
}
//cout << numTwo << endl; // This line would give a compile error
}
In this example, numZero is global, numOne is local to the main() function, while numTwo is local to the if statement code block only. Trying to use numTwo outside the if statement code block would break the code, since it is undeclared outside that scope.
When multiple variables have the same name, the more local variable takes precedence. A global variable can still be used by using the scope resolution operator (::). Example:
int numZero = 3;
int main(){
int numZero = 10;
cout << ::numZero << endl;
}
This outputs 3, not 10, because the scope resolution operator resolves the scope of numZero to global instead of local.
for loops and scope
If a variable is declared within the initialization of a for loop, that variable has scope only within the for loop itself. In the example:
for(int i=0; i<10; i++) {
//statements
}
The variable i is only defined locally within the loop itself.