Introduction
Variables and constants are fundamental building blocks of any C++ program. They are used to store and manage data during the execution of a program. Variables represent storage locations that can be changed during runtime, whereas constants represent fixed values that cannot be altered once defined. Proper usage of variables and constants leads to better code structure, reusability, and maintainability. C++ offers a rich set of data types and storage classes that help manage how variables are stored and accessed in memory. Understanding their behavior is crucial for efficient programming.
Variables in C++
Variables in C++ Variables in C++ are named storage locations used to hold data, and each has a specific type that determines the kind of values it can store. Common types include int, float, char, and bool, and variables must be declared before use to allocate memory and define behavior.
General Syntax:
<data_type> <variable_name> = <value>;
Example:
int age = 25;
float temperature = 36.5;
Types of Variables
- Local Variables: Declared inside a function or block and accessible only within that scope.
Example:-
void show() {
int x = 10; // local variable
}
- Global Variables: Declared outside all functions and accessible throughout the program.
Example:-
int g = 5; // global variable
void show() {
cout << g;
}
- Static Variables: Retain their values between function calls.
Example:-
void counter() {
static int count = 0;
count++;
cout << count;
}
- Automatic Variables: By default, local variables are auto. Declared using auto keyword (C++11 onwards).
Example:-
auto a = 10; // type automatically inferred
- Register Variables: Suggests storing variable in CPU register for faster access.
Example:-
register int speed = 50;