A variable is a named location in memory reserved to hold a value that can be modified during program execution. In C++, every variable has a specific data type, memory address, scope of visibility, and lifetime.
// 1. C-style Assignment (Legacy)
int a = 10;
// 2. Constructor / Functional Initialization (Direct)
int b(20);
// 3. Uniform / Brace Initialization (Modern C++11 Recommended)
int c{30}; // Safe: Prevents narrowing conversions!
int d{}; // Value-initialized to 0 automatically
{ }?
Brace initialization stops dangerous data loss at compile time. For example, int x = 7.9; silently truncates to 7 with a warning. But int x{7.9}; causes a compilation error because narrowing from double to int is forbidden!
{ }. Created when entering the block and destroyed when exiting (Stack memory).namespace App { int score; }).static Local Variables#include <iostream>
void countVisits() {
static int visitorCount = 0; // Initialized ONLY ONCE!
visitorCount++;
std::cout << "Visitor #" << visitorCount << std::endl;
}
int main() {
countVisits(); // Output: Visitor #1
countVisits(); // Output: Visitor #2
countVisits(); // Output: Visitor #3
return 0;
}
auto Type Deduction (C++11)The auto keyword tells the C++ compiler to automatically deduce the variable's type from its initialization expression at compile time:
auto age = 22; // Deduces int
auto pi = 3.14159; // Deduces double
auto letter = 'Z'; // Deduces char
auto message = "Veewom"; // Deduces const char*
Boost your C++ proficiency by studying these closely connected core modules:
Primitive and derived types and their byte sizes.
Accepting values into variables from the user.
Inspecting the physical memory addresses of variables.