What is a Variable?
A variable is a named memory location that can store data during the execution of a program. It acts as a symbolic representation of a specific memory address allowing programmers to work with easily identifiable and manipulable data.Types of Variables in C++
C++ supports various data types for variables. The common types include:Primitive Data Types:
- int: Integer data type.
- float: Floating-point data type.
- double: Double-precision floating-point data type.
- char: Character data type.
- bool: Boolean data type.
Derived Data Types:
- Array: A collection of elements of the same data type.
- Pointer: A variable that stores the memory address of another variable.
- Reference: An alias for an existing variable.
User-Defined Data Types:
- struct: Allows grouping variables of different data types under a single name.
- class: Blueprint for creating objects with related data and functions.
- enum: Enumerated data type with symbolic names.
Declaring and Initializing Variables
In C++, a variable must be declared before it can be used. The syntax for declaring a variable is:data_type variable_name;
For example:
int age;
float price;
char grade;
Variables can also be initialized during the declaration:
int count = 10;
double pi = 3.14;
char symbol = 'A';
Rules for Naming Variables
- Variable names are case-sensitive (myVar and myvar are different).
- Variable names can include letters, digits and underscores.
- The first character must be a letter or an underscore.
- Reserved words (keywords) cannot be used as variable names.
Using Variables in C++ Programs
Once declared and initialized variables can be used for the various operations including arithmetic calculations, comparisons and more.#include <iostream>
int main() {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
std::cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;
return 0;
}
output :
Sum of 5 and 10 is: 15