2. What is Scope?
The
“scope” of a variable means the
places in your code you can use it.
All of our variables so far have been
declared in blocks of code delineated by {
} (such as the int main() function or other
function, as well as loops and conditionals.
If a variable is declared in a block, it can
only be used in that block (and subblocks).
4. Functions
A
function cannot access a variable
declared in the main() method, unless the
value of that variable is passed as a
parameter.
In the function there will now be a copy of
the original value.
Changing the value of the variable in the
called function, does not affect its value
elsewhere.
5. Example
void func(int x){
x = 10;
}
int main(){
int n = 5;
func(n);
cout<<n; //Outputs 5, NOT 10.
}
Value of “x” is lost once function is completed.
6. Example 2
int func(int x){
x = 10;
return x;
}
int main(){
int n = 5;
n = func(n);
cout<<n; //Outputs 10.
}
7. Pass by Reference
In
C++ we can give a function access to
the original variable itself, by passing a
“reference” to it. (The reference being the
address of the variable in memory.)
Then any changes done to it in the
function remain in effect.