Variables
A variable in C++ is a named piece of memory that holds a value. Unlike Python or JavaScript, C++ is statically typed — every variable must be declared with a specific type, and that type is fixed for the lifetime of the variable. The compiler uses the type to figure out how much memory to reserve and what operations are valid on the value.
#include <iostream>
int main() {
int age = 25; // integer variable
double price = 19.99; // floating-point variable
char grade = 'A'; // single character
bool isValid = true; // true or false
std::cout << age << " " << price << " " << grade << " " << isValid << std::endl;
return 0;
}Naming Rules and Conventions
C++ enforces a few hard rules for identifiers, plus some conventions the community generally follows.
Names can contain letters, digits, and underscores only
A name cannot start with a digit (
1valueis illegal,value1is fine)Names are case-sensitive (
ageandAgeare different variables)Reserved keywords (
int,class,return,for, etc.) cannot be used as identifiersNames starting with an underscore followed by a capital letter, or a double underscore, are reserved for the implementation — avoid them
Convention varies by codebase: many C++ style guides (Google, LLVM-influenced projects) prefer camelCase for local variables (totalScore) or a mix of camelCase and snake_case for members and functions, while other codebases (STL itself, many game engines) prefer snake_case throughout (total_score). Neither is "more correct" — pick one convention per project and stay consistent.
Initialization Styles
C++ offers several ways to give a variable its first value. Modern C++ (11 and later) encourages brace initialization because it is more consistent and catches mistakes the older styles miss.
Syntax | Name | Notes |
|---|---|---|
int x = 5; | Copy initialization | Familiar C-style; allows implicit narrowing conversions |
int x(5); | Direct (functional) initialization | Common in constructor initializer lists |
int x{5}; | Brace / uniform initialization | Preferred in modern C++; rejects narrowing conversions |
int x{}; | Value initialization | Zero-initializes to a sane default (0 for int) |
int a = 5; // copy-init
int b(5); // direct-init
int c{5}; // brace-init (preferred)
int d{}; // value-init -> d is 0
// Brace init catches narrowing at compile time:
int e{3.14}; // ERROR: narrowing conversion from double to int
int f = 3.14; // compiles silently -> f becomes 3 (data loss!)Always initialize variables when you declare them:
int score; // uninitialized — value is indeterminate garbage
std::cout << score; // undefined behavior: reads garbage memory
int safeScore{}; // value-initialized to 0 — always safe