Advertisement
Felanpro

Explanation Of GlobalVariables And LocalVariables.

Nov 3rd, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. LocalVariables are variables that are declared within a function or block of code.
  2. Their scope is limited from the point of declaration to the end of the function or block in wich they are declared.
  3. Their lifetime is from entering the function/block to the termination of the function/block or easily said to the end of the function/block.
  4.  
  5. For example:
  6.  
  7. int main()
  8. {
  9. string hey = "Hey!";      //Declaration
  10.  
  11. cout << hey << endl;      //This will print Hey! on the screen.
  12. system("pause");
  13. }
  14.  
  15. int anotherFunctionHere()
  16. {
  17. cout << hey << endl; //But if we wanted to use that variable declared in int main() function it wouldn't work in int
  18. anotherFunctionHere because it's local.
  19. }
  20.  
  21.  
  22.  
  23. GlobalVariables are variables declared outside of any function. Global variables are accessible in every scope.
  24. Global variables persist in memory for the duration of the program.
  25.  
  26. For example:
  27.  
  28. #include <iostream>
  29. #include <string>
  30. #include <math.h>
  31. #include <math.c>
  32. using namespace std;
  33.  
  34. string coolStringName = "Hola!"; // As you can see the variable is declared outside of a function. So it doesn't belong anywhere
  35.                                  //unless you use it in a function :)
  36.  
  37. int main()
  38. {
  39. cout << "blablabla" << endl;
  40. cout << "Epic code written here!" << endl;
  41. }
  42.  
  43. int coolAwesomeCode()
  44. {
  45. cout << "more blablabla" << endl;
  46. cout << "i'm getting bored of typing blablabla" << endl;
  47.  
  48. cout << coolStringName << endl; //And know this will work :)
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement