In C++, a variable is a named storage location in memory that holds a value, which can be modified during the execution of the program. Each variable has a name and a type that tells you what kind of value it can store, such as integers, floating-point numbers, characters, etc.
Characteristics About C++ Variables
Declaration: Before you can use a variable, it must be declared. When declaring a variable, you specify its type and name.
Initialization: You can assign a value to the variable at the time of declaration, or assign it later in the program.
Scope: The scope of a variable defines where it can be accessed. For example, variables declared inside a function are local to that function.
Lifetime: The lifetime of a variable is the period during which it exists in memory. Local variables are created when the program execution enters the block in which they are defined, and they are destroyed when execution leaves that block.
Rules of Variable
1. A variable name must start with a letter (a-z, A-Z) or an underscore (_).
2. The rest of the variable name can contain letters, digits (0-9), and underscores.
3. Variable names cannot be C++ keywords (e.g., int, if, return).
4. Variable names are case-sensitive (e.g., age and Age are different variables).
Example of Variable Declaration and Initialization:
#include <iostream>
#include <string> // For using the string type
using namespace std;
int main() {
string name = "John"; // string variable
int age = 35; // integer variable
bool isManager = true; // boolean variable
char grade = 'A'; // character variable
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Manager: " << isManager << endl;
cout << "Grade: " << grade << endl;
return 0;
}
Output:
Age: 35
Manager: 1
Grade: A