Untitled
By: a guest | Mar 18th, 2010 | Syntax:
C++ | Size: 1.95 KB | Hits: 63 | Expires: Never
// local variables exist until the next }
void Function()
{
int foo; // this is declared in a function
// therefore it is local (local to 'Function')
// this variable does not exist anywhere else in the program. IE: you can't access
// 'foo' from a different function because it only exists inside 'Function'
} // this is the end of the function. Here, foo dies (goes out of scope)
void Another()
{
int butt = 0;
if(butt == 0)
{
int bar; // this is another local var. But it is local to the 'if' statement
// inside 'Another', and will die as soon as the if statement ends
} // so 'bar' dies here
butt = bar; // error -- 'bar' no longer exists
int foo; // we create another variable named foo
// note that this variable is TOTALLY DIFFERENT
// from the 'foo' in Function, even though
// they have the same name. They are two seperate variables.
}
// With structs/classes, it's a little different:
class MyClass
{
public:
int a; // 'a' is a "member" of MyClass. It is not local.
// 'a' exists in every object of MyClass. IE: every 'MyClass' has it's own 'a'
// and each 'a' can have it's own value.
void MemberFunc1()
{
// this is a member function of MyClass
// since it's a member, all member variables are in scope
// ie: 'a' exists here
a = 10; // OK!
}
void MemberFunc2()
{
// same deal, the same 'a' exists here:
a = 5; // OK!
}
};
int main()
{
MyClass disch; // here we create an 'object' of type 'MyClass' named 'disch'
MyClass sivak; // and here's sivak
// disch and sivak are two different objects. they each have their own 'a', so each 'a' is different:
disch.a = 5;
sivak.a = 10;
// sivak's a is bigger than disch's a =(
} // sivak and disch die here
// and therefore, all their members die