C++ Tutorial for beginners – Variables

Basics of C++ | Variables | If statements | Loops | Functions

 

 

 

Just compile this and see what happens.

1

2

3

4

5

6

7

8

9

10

11

#include <iostream.h>

 

int x = 5;

 

int main()

{

            int x = 2;

            cout << "Global x: " << :: x << endl;

            cout << "Local x: " << x << endl;

            return 0;

}

You will get:

Global x: 5

Local x: 2

 

 

3

int x = 5;                            

 

This is defined outside of main() so it can be shared with all other functions and not just main. If this was defined in main() then main() is the only function that can get or set the value of it.

 

7

int x = 2;                            

 

This is defined in main() so it is local. It cannot be used outside of main() unless it is passed through when calling another function

 

8

cout << "Global x: " << :: x << endl;     

 

Notice :: x. This is basically telling the compiler to look for x outside of main()

 

9

cout << "Local x: " << x << endl;         

 

This is just getting the local x value, so the value to this would just be 2