Demonstrating global and local variables in C++

By: Priya Emailed: 1674 times Printed: 2155 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Variables defined outside of any function have global scope and thus are available from any function in the program, including main().

Local variables with the same name as global variables do not change the global variables. A local variable with the same name as a global variable hides the global variable, however. If a function has a variable with the same name as a global variable, the name refers to the local variable--not the global--when used within the function. Program below illustrates these points.

Demonstrating global and local variables.

1:   #include <iostream.h>
2:   void myFunction();           // prototype
3:
4:   int x = 5, y = 7;            // global variables
5:   int main()
6:   {
7:
8:        cout << "x from main: " << x << "\n";
9:        cout << "y from main: " << y << "\n\n";
10:       myFunction();
11:       cout << "Back from myFunction!\n\n";
12:       cout << "x from main: " << x << "\n";
13:       cout << "y from main: " << y << "\n";
14:       return 0;
15:  }
16:
17:  void myFunction()
18:  {
19:       int y = 10;
20:
21:       cout << "x from myFunction: " << x << "\n";
22:       cout << "y from myFunction: " << y << "\n\n";
23: }

Output: x from main: 5
y from main: 7

x from myFunction: 5
y from myFunction: 10

Back from myFunction!

x from main: 5
y from main: 7

Analysis: This simple program illustrates a few key, and potentially confusing, points about local and global variables. On line 1, two global variables, x and y, are declared. The global variable x is initialized with the value 5, and the global variable y is initialized with the value 7.
On lines 8 and 9 in the function main(), these values are printed to the screen. Note that the function main() defines neither variable; because they are global, they are already available to main().

When myFunction() is called on line 10, program execution passes to line 18, and a local variable, y, is defined and initialized with the value 10. On line 21, myFunction() prints the value of the variable x, and the global variable x is used, just as it was in main(). On line 22, however, when the variable name y is used, the local variable y is used, hiding the global variable with the same name.

The function call ends, and control returns to main(), which again prints the values in the global variables. Note that the global variable y was totally unaffected by the value assigned to myFunction()'s local y variable.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

Very helpful and easily understandable!

View Tutorial          By: Teerna at 2014-11-12 23:55:49

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Priya
Getting started with ASP
EJB Entity Beans
Error Handling - Stderr and Exit - sample program in C
Pointers and Arrays in C
Data Types and Sizes in C
virtual inheritance example in C++
ctime() sample program in C++
TextBox sample program in J2ME
Advantages of Java Beans
list() contents of a Directory - sample program in Java
File example program in Java
continue and break statements in C++
Use of 'throw' in Java
Passing parameters to a function by value in C++
Demonstrating global and local variables in C++

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
C++ Recursion function explained using Fibonacci series
Sorting an array of Strings in C++
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Using cout.width() in C++
virtual inheritance example in C++
Public versus Private members in C++
Where to Put Class Declarations and Method Definitions in C++
Calculating total based on the given quantity and price in C++
The Birth, history and need for C++
while Loops in C++
while (1) Loops in C++
Converting C++ Multiple-Inheritance Hierarchies to Java
qsort() sample program in C++
ctime() sample program in C++
Most Emailed Articles (in C++)
Looping with the keyword goto in C++
Default arguments in C++
Compiling and Linking Multiple Source Files in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Tutorial on Classes and Members in C++
for Loops in C++
Using switch Statements in C++
Operator Precedence in C++
How to handle Exceptions in C++
strcpy() and strncpy() sample program in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Function overloading in C++
File in C++ - Writing text to a file in C++
Pass by Reference vs Pass Value in C++ functions