Variables are fundamental building blocks in C++ programming, serving as named memory locations that store data. This comprehensive blog dives into the essentials of variables, including their declaration, definition, and initialization. You’ll learn about the rules for naming variables, such as camel case, snake case, and uppercase conventions, and explore examples of valid and invalid variable names.
The blog also examines the three key types of variables in C++—local, global, and static—detailing their scope, lifetime, storage, and initialization. Through practical examples and programs, you’ll understand the nuances of variable usage, such as the difference between declaration and definition, and the unique behavior of static variables in local scope.
// Declaring a single variable
type variable_name;
// Declaring multiple variables:
type variable1_name, variable2_name, variable3_name;
Rules For Declaring Variable
camel case: typically used for variable names in c++ (e.g., firstname, studentage).
snake case: another option (e.g., first_name, student_age).
uppercase: constants are often written in uppercase letters with underscores separating words (e.g., max_size).
———————————–
int a; //can be letters
int _pa; //can be underscores
int a55;//can be letters
invalid variable name
————————————
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;
Variable declaration and definition:
————————————————————
// C++ program to show difference between
// definition and declaration of a
// variable
#include <iostream>
using namespace std;
int main()
{
int a; // declaration part
a = 5;//initialization
int myvariable= 20; //definition = declaration + initialization
char b56 = ‘b’;/*declaration and definition */
float c;// declaration+definition and assigns some garbage value
// multiple declarations and definitions
int _myvariable, _myvariable1, e;
// Let us print a variable
cout << a123 << endl;
return 0;
}
————————-
There are three types of variables based on the scope of variables in C++
Local Variables
Instance Variables
Static Variables
Program that differentiates the local variables ,global variables and static variables
#include<iostream.h>
class vehicle
{
public:
static int a; // static varaiable
int b; // global variable
public:
func()
{
int c; // local variable
}
};
Comparison of Local, Global, and Static Variables
Aspect | Local | Global | Static Local |
Scope | Within the block | Entire program | Within the block |
Lifetime | Until block exits | Program’s lifetime | Program’s lifetime |
Storage | Stack | Global memory | Global memory |
Initialization | Every time block runs | Once, before main() runs | Once, when function runs |
Indian Institute of Embedded Systems – IIES