CS111 Lab
Scope of Variables
Instructor: Michael Gordon
What is Scope?
 The

“scope” of a variable means the
places in your code you can use it.
 All of our variables so far ha...
Example
for(int i=0;i<=10;i++){
cout<<i; //outputs “i"
}
cout<<i; //error!
This is true even without { }
for(int i=0;i<=10...
Functions
A

function cannot access a variable
declared in the main() method, unless the
value of that variable is passed...
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 o...
Example 2
int func(int x){
x = 10;
return x;
}
int main(){
int n = 5;
n = func(n);
cout<<n; //Outputs 10.
}
Pass by Reference
 In

C++ we can give a function access to
the original variable itself, by passing a
“reference” to it....
Example
void func(int &x){
x = 10;
}
int main(){
int n = 5;
func(n);
cout<<n; //Outputs 10.
}
Upcoming SlideShare
Loading in...5
×

Scope of variables

571

Published on

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
571
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Scope of variables

  1. 1. CS111 Lab Scope of Variables Instructor: Michael Gordon
  2. 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).
  3. 3. Example for(int i=0;i<=10;i++){ cout<<i; //outputs “i" } cout<<i; //error! This is true even without { } for(int i=0;i<=10;i++) cout<<i; //outputs “i" cout<<i; //error!
  4. 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. 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. 6. Example 2 int func(int x){ x = 10; return x; } int main(){ int n = 5; n = func(n); cout<<n; //Outputs 10. }
  7. 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.
  8. 8. Example void func(int &x){ x = 10; } int main(){ int n = 5; func(n); cout<<n; //Outputs 10. }
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×