Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 18th, 2010 | Syntax: C++ | Size: 1.95 KB | Hits: 63 | Expires: Never
Copy text to clipboard
  1. // local variables exist until the next }
  2.  
  3. void Function()
  4. {
  5.   int foo;  // this is declared in a function
  6.             //  therefore it is local (local to 'Function')
  7.             // this variable does not exist anywhere else in the program.  IE:  you can't access
  8.             // 'foo' from a different function because it only exists inside 'Function'
  9.  
  10. }  // this is the end of the function.  Here, foo dies (goes out of scope)
  11.  
  12. void Another()
  13. {
  14.   int butt = 0;
  15.   if(butt == 0)
  16.   {
  17.     int bar;  // this is another local var.  But it is local to the 'if' statement
  18.               //  inside 'Another', and will die as soon as the if statement ends
  19.  
  20.   } // so 'bar' dies here
  21.  
  22.   butt = bar;  // error -- 'bar' no longer exists
  23.  
  24.   int foo;  // we create another variable named foo
  25.             //  note that this variable is TOTALLY DIFFERENT
  26.             //  from the 'foo' in Function, even though
  27.             //  they have the same name.  They are two seperate variables.
  28. }
  29.  
  30.  
  31. //  With structs/classes, it's a little different:
  32.  
  33. class MyClass
  34. {
  35. public:
  36.   int a;   // 'a' is a "member" of MyClass.  It is not local.
  37.            // 'a' exists in every object of MyClass.  IE:  every 'MyClass' has it's own 'a'
  38.            //   and each 'a' can have it's own value.
  39.  
  40.   void MemberFunc1()
  41.   {
  42.     // this is a member function of MyClass
  43.     //  since it's a member, all member variables are in scope
  44.     //  ie:  'a' exists here
  45.     a = 10;  // OK!
  46.   }
  47.  
  48.   void MemberFunc2()
  49.   {
  50.     // same deal, the same 'a' exists here:
  51.     a = 5; // OK!
  52.   }
  53. };
  54.  
  55.  
  56. int main()
  57. {
  58.   MyClass disch;  // here we create an 'object' of type 'MyClass' named 'disch'
  59.   MyClass sivak;  // and here's sivak
  60.  
  61.   // disch and sivak are two different objects.  they each have their own 'a', so each 'a' is different:
  62.   disch.a = 5;
  63.   sivak.a = 10;
  64.  
  65.   // sivak's a is bigger than disch's a  =(
  66. }  // sivak and disch die here
  67.    // and therefore, all their members die