In this C++ Tutorial we are going to talk about Local Variable Vs Global Variable in C++,
so you can use C++ Variables inside a function in different ways. you can use Variables as
arguments when you are going to call a function. also variables can be shared by the function
and rest of a program. you can create variables in a function locally and globally.
Learn Python GUI Development
1: PyQt5 GUI Development Tutorial
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
5: TKinter GUI Development Course
Also you can learn C++ GUI development with Qt5 Framework
1: Qt5 C++ GUI Development Tutorials
Local Variables
When you create a variable inside a function it is called local variable. because it exists
only locally within the function itself. When the function returns, all of its local variables
are no longer available for use in the program. you can create local variables like normal
variable creation.
So now let’s create our local variable example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<iostream> using namespace std; int main() { int a = 7; int b = 8; int sum = a + b; cout << sum << '\n'; return 0; } |
You can see in the above example i have created three local variables inside my main() function.
This is the output:
1 2 |
15 Press any key to continue . . . |
Global Variable
You can create a variable outside of the function in C++, when you create a variable
outside of a function that is called Global Variable, because they are available everywhere
in the program.
Now let’s take a look at this example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include<iostream> using namespace std; //Global variables int a; int b; int sum; int main() { // getting the number from the user input cout << "Please enter first number " << '\n'; cin >> a; cout << "Please enter second number : " << '\n'; cin >> b; //adding the numbers sum = a + b; //printing the outpu cout << "Sum is : " << sum << '\n'; return 0; } |
So you can see that we have created three variables outside of our main() function,
you can access to this variables in every where of the program.
In this program we are going to just asks two numbers from the user and after that
we are adding these two numbers and print the output in the terminal.
Execute the code this will be the result for C++ Tutorial – Local Variable Vs Global Variable.
1 2 3 4 5 6 |
Please enter first number 6 Please enter second number : 4 Sum is : 10 Press any key to continue . . . |
Subscribe and Get Free Video Courses & Articles in your Email