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.
In order to use a variable in C++, we must first declare it specifying which data type we want it to be.
The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float…) followed by a valid variable identifier.
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
C++ Variable – Questions and Answers
Q 1: What is a variable?
Ans: A variable stores data that can change during program execution.
Q 2: How do you declare a variable?
Ans: int a;
Q 3: Can variable names start with numbers?
Ans: No.
Q 4: What is variable initialization?
Ans: Assigning a value at the time of declaration.
Q 5: Are variable names case-sensitive?
Ans: Yes.
C++ Variable – Objective Questions (MCQs)
Q1. Which of the following is the correct way to declare a variable in C++?
Q2. Which of the following is a valid variable name in C++?
Q3. What is the correct syntax to assign value 10 to a variable x in C++?
Q4. Which of the following statements about variables in C++ is true?
Q5. What will be the output of the following code?
int a = 5;
int b = a + 2;
cout << b;