Remove Ads

Share on Facebook Share on Twitter

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tutorial on Scope
#1
What is scope? Well scope is how something relates to the program, whether globally or locally, it's important to know how it works.

Think of local variables like levels in a video game.
[code]
void level2()
{
int x = 12;
}

void level1()
{
int x = 2;
}
[/code]
The reason this compiles fine is because x only exists in the scope of its function. This is normally a good thing and be very sure when you want to make global variables.

[code]
int x = 12;

void level1()
{
//do something
}

void level2()
{
//do something
}
[/code]

Now you cannot use x again as a variable because it is global. However this means you can use it in any function you want.

Scope is important to realise when passing variables or just calling functions.
Consider this,
[code]
int main()
{
Func();
}

void Func()
{
//Do something
}
[/code]
This will produce a, "Func is undeclared" error. The reason this happens is because the compiler reads left-to-right and up-to-down.

This means now this will work because the compiler knows what Func isCool.
[code]
void Func()
{
//Do something
}
int main()
{
Func();
}[/code]

However if you want Func below main that's entirely possible.
Just be sure to declare to the compiler that your going to have a function called Func. Here's an example.
We declare of a future function and the program will run fine.
[code]
void Func();

int main()
{
Func();
}

void Func()
{
//Do something
}
[/code]

So now about passing variables. That's what the () in a function are for.
[code]
void Func(int a)
{
// Do something
}

int main()
{
int b = 12;
Func(b);
}
[/code]
Wondering how this works?
Remember how I said variables are local to that function?
Your passing a copy of the value of b into the int a in Func.
Func then stores a copy of b's value in it's own local variable a.
It's important to realise this because what if you want to directly edit b?Huh

This is where pointers/references come in.
[code]
#include <iostream>

void Func(int &b)
{
++b;
std::cout<<b;
}

int main()
{
int b = 20;
int *a = &b;
Func(*a);
std::cin.get();
return 0;
}
[/code]
Using these will allow you to edit local variables in different fuctions without making them global.

This concludes my intro to scopeTongue.
Reply
#2
Very nice, it explains the concept clearly and is easy to understand. It's a pretty basic concept but important to know.
Reply
#3
Indeed, another important post.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)