Updated April 7, 2023
Definition of Local Variable C++
A local variable is defined, initial values set and consumed within a function or method, or block. These variable gets life only when the function where the variable exists is executed and gets destroyed automatically when program control passes to next function. The program returns an error if a local variable is referred outside its function or method or block.
A local variable in C++ identifies value stored in the memory location by a name.
The boundary limit (Scope) within which variables in C++ operate, characterizes whether it is a local or global variable.
Syntax
It basically consists of the definition and declaration of local variables
Local Variable Definition
Local variable definition in C++ involves
- Local Variable Name
- Data type
- Initial value
Initial value can be part of the definition statement or it can be a separate statement.
Any definition statement should be terminated with a semicolon otherwise it will result in an error. Multiple variables with the same data type can be clubbed together in a single statement within a function
Syntax:
data-type local-variable-name = initial-value;
int rate = 400; char empname = 'XYAZ', option = '1';
rate, empname, option are local variable names.
int, char are data types.
400, 'XYAZ', '1' are initial values
1. Local Variable name
Certain rules will have to be adhered to in naming a local variable
1. Should always start with alpha or “_” underscore
2. Should never start with a numeric character
3. It is case sensitive and a name with capital letters and lowercase are considered as two different variables
4. Should never contain spaces, graphic symbols, and special characters
5. Variable names should never be duplicated within a function or method or block.
6. Keyword should never be used as a variable name
Valid names – studentname, PONO, _supplier, PaRTno
Invalid names – Order@no, marks#, 788supplier
2. Data Type
It specifies the type of data the local variables will hold during program execution. Integer, Characters are some of the familiar types.
Data types are broadly classified into three groups
Group | Data types |
Built-in | Str (Alphanumeric),
Int(Integers), Float (Floating point single precision), Double (Floating point double precision), wide char, Boolean (true or false) Void (no value returned) |
User-Defined | Enum, Union, Structure |
Derived in Program | Pointer, Function, Array |
3. Initial value
Value defined to hold at the beginning of program execution and it should be the same as the data type defined. Any wrong assignment will be thrown out as an error.
Local Variable Declaration
Definition of a variable instructs the compiler to allot memory and variable can be defined only once but a declaration of a variable is just information to complier and it can be done many a time and it will not consume memory. Syntax for declaring a variable is:
extern int a ; (Name and data types are similar to variable definition)
It only declares to the compiler that local variable ‘a’ with data type integer will be used in the program somewhere and it will be defined later.
How Local Variable in C++ Works?
Local variables are defined within a function or method or block and its scope of operation is restricted within the unit and it cannot be referred or used for storing results outside the scope. Local variables get activated when that function is executed, all the operations take place using these variables and the results are stored in these variables as per the program flow.
Once the function is executed the local variables will lose it importance and they will be removed from the memory.
Local variable can either be defined as parameters in the definition of function or as a separate statement in the body of the function.
Examples
Below are the examples mentioned:
1. Compute Average
Code:
#include <iostream>
using namespace std;
int average1(int totalmarks, int students) {
return totalmarks / students;
}
int main() {
int tm = 600, s = 50;
int avg;
avg = average1(tm, s);
cout << "The Average marks in the class is : "<< avg << endl;
return 0;
}
Output:
In the above example
- In function average1, two local variables namely total marks, students are declared along with the definition of the function. These two local variables have importance only within this function and have no relevance outside. This function returns results in integer format.
- In function main two local variables tm, s are defined in a separate statement with an initial value of 600, 50 respectively. Another local variable avg is defined to store results. Variables tm,s,ag have relevance with main and the values in it will get destroyed once the execution is completed.
- In function main the function average1 is called using the variables tm and s.
- Function average1 substitutes tm,s with totalmarks, students respectively and computes the result by dividing them
- The results are returned and stored in the local variable avg in function main and the result is displayed.
- All the variables are integers.
2. Same local variable name in different functions
Code:
#include <iostream>
using namespace std;
void mornfun() {
string disp1;
disp1 = "Good morning";
cout << disp1 << endl;
}
void evenfun() {
string disp1 = "Good Evening";
cout << disp1 << endl;
}
int main() {
mornfun();
evenfun();
return 0;
}
Output:
In the above program, the same local variable disp1 is used in the functions mornfun, evenfun, and both the functions are called from another function main. Local variable disp1 performs the assigned activity within function more fun, gets initialized at the end, and starts new activity in the function evenfun. Operations of variable disp1 in function mornfun have no relationship with the same variable in the other function and they are purely local in nature.
Conclusion
Meaning and significance of local variables were amply explained with examples in this article.
Recommended Articles
This is a guide to Local Variable in C++. Here we discuss definition, syntax, working of Local Variable in C++ along with examples and code implementation. You may also have a look at the following articles to learn more –