![]() |
Prerequisites: Scope of Variables, Data Types, and Functions in C++ In C++ programming languages, a variable is a name provided to memory to store different data types. Variable values can change anytime while running the program and each variable has its own scope (or region) where it is valid to access the variable using the name given to him. In programming, variables are not all equal. Their scope, lifespan, and accessibility in the program depend on where and how they are declared. There are two types of variables based on their scope.
Global Variable in C++Global variables are the variables that are declared outside of any function or class and can be accessed by any part of the program. They are generally declared at the beginning of the source file after the header file. They are available throughout the lifetime of a program and accessible from anywhere within the program. Declaration of a Global Variable in C++To create a global variable, we simply declare it at the top of the source file, after the header files, and before the main function. In C++, all the variables must be declared before use. Example 1C++
Output
10 Explanation
Now, someone might wonder why you would want to use global variables in your program. Example 2C++
Output
5 10 Explanation
Benefits of Using Global VariablesFollowing are some main benefits that global variables provide:
Drawbacks of Using Global VariablesGlobal variables also come with some drawbacks. Some of them are:
ConclusionGlobal variables are very useful but ‘difficult to track’ variables in C++ programming language. They are useful because we can access the same variable in any part of the program but it must be used such that it doesn’t make code less readable and less maintainable, and also takes care of security aspects. Therefore, it is suggested to use global variables rarely and carefully and prefer local variables or other alternatives whenever possible. |
Reffered: https://www.geeksforgeeks.org
C++ |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |