Variables In C++
Topic asked in March 2021 (CBCS) question paper.
Variables are containers for storing data values. It is the basic unit of storage in a program. They are used to assign a memory location to data types. The value stored in a variable can be changed during program execution. In C++, all the variables must be declared before use.
Declaration / Initialization Of Variables
A typical variable declaration and initialization is of the form:
Here,
- data_type: Type of data that can be stored in this variable.
- variable_name: Name given to the variable.
- value: It is the initial value stored in the variable.
Variable Definition = Declaration + Initialization. A variable definition is a part where the variable is assigned a memory location and a value.
Using Built-In Data Types
Note: The int
data type suggests that the variable can only hold
integers. Similarly, we can also use the double
data type if we have to
store decimals and exponentials.
Rules For Declaring Variable
- The name of the variable contains letters, digits, and underscores.
- The name of the variable is case sensitive (ex Arr and arr both are different variables).
- The name of the variable does not contain any whitespace and special characters (ex #,$,%,*, etc).
- All the variable names must begin with a letter of the alphabet or an underscore(_).
- We cannot used C++ keyword (ex float,double,class) as a variable name.
Valid Variable Names:
- int s; //can be letters
- int _sd; //can be underscores
- int a35; //can be letters
Invalid Variable Names:
- int 25; //Should not be a number
- int a b; //Should not contain any whitespace
- int double; // C++ keyword CAN NOT BE USED
Types of Variables
Topic asked in July 2022 (CBCS) question paper.
Some types of variables in C++ -
- Local Variables
- Global Variables
- Static Variables
Let us now learn about each one of these variables in detail.
-
Local Variables
Local variables are declared inside the function. Local variables must be declared before they have used in the program. Functions that are declared inside the function can change the value of variables. Functions outside cannot change the value of local variables.
Here is an example:-
-
Global Variables
Global variables are declared outside the functions. Any functions i.e. both local function and global function can change the value of global variables.
Here is an example:-
-
Static Variables
These variables are declared with the word static. When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of the variable in the previous call gets carried through the next function call.
Here is an example:-
Last updated on -