C++ Basics: Variables
Learn how to declare, initialize, and control the scope and lifetime of variables in C++.
Variable Declaration and Initialization
A variable is a named storage location. Declaration tells the compiler the type and name; initialization assigns an initial value. In C++ you should always initialize variables before reading them, uninitialized variables hold garbage values.
Declaration vs Initialization
Declaration reserves memory; initialization sets the starting value. Both together in one line is the safest habit.
- Declaration: int age; (memory reserved, value is undefined)
- Initialization: int age = 20; (memory reserved and value set)
- Uniform initialization (C++11): int age{20}; (preferred, prevents narrowing)
- Reading an uninitialized variable is undefined behavior, always initialize
Declaring and Initializing Variables
C++Two initialization styles, both are correct.
Multiple Variable Declaration
You can declare multiple variables of the same type in a single statement, separated by commas. Each can have its own initializer.
Multiple Declarations
Declaring multiple variables per line can save space, but only do it when they are closely related, otherwise separate lines are clearer.
- int a = 1, b = 2, c = 3; declares and initializes three ints
- int x, y; declares two ints, both uninitialized
- int a = 1, b; a is 1, b is uninitialized (risky)
- Never mix types on the same declaration line
Multiple Variable Declaration
C++Declare and initialize three related variables in one statement.
Constants
The const keyword marks a variable whose value cannot change after initialization. The compiler will reject any attempt to modify it.
const
Prefer const over magic numbers, it gives the value a name and prevents accidental modification.
- A const variable must be initialized when declared
- const double PI = 3.14159; makes PI immutable
- constexpr (C++11) additionally guarantees the value is computed at compile time
- Use ALL_CAPS naming for constants by convention
Using const
C++PI cannot be changed after initialization, the compiler enforces this.
Literals
A literal is a fixed value written directly in the source code. C++ supports integer, floating-point, character, and string literals, each with its own syntax and optional suffixes.
Literal Types
Suffixes let you explicitly control the type of a literal so it matches the variable you are assigning it to.
- Integer: 42, -7, 0xFF (hex), 0b1010 (binary C++14), 077 (octal)
- Float: 3.14 (double), 3.14f (float), 3.14L (long double)
- Character: 'A', '\n' (newline), '\t' (tab)
- String: "Hello", a null-terminated array of char
- Boolean: true, false
Literals in Code
C++Hex integer, float suffix, and a character literal used together.
Scope of Variables
Scope defines where in the code a variable is accessible. Local variables exist only inside the block where they are declared; global variables are accessible from any function in the file.
Local vs Global Scope
Prefer local variables, they are easier to reason about and do not pollute the global namespace.
- Local variable: declared inside a function or block { }; destroyed when the block ends
- Global variable: declared outside all functions; lives for the entire program
- A local variable with the same name as a global shadows the global inside its block
- Excessive use of global variables makes code hard to test and maintain
Local vs Global Scope
C++globalCount is visible in both functions; local is not.
Static Variables
A static local variable retains its value between function calls. It is initialized only once, the first time the function runs.
static
Use static locals when a function needs to remember state between calls without exposing a global variable.
- Initialized once at program start (or first call); never re-initialized
- Stays alive for the entire program, but only accessible inside its scope
- static at file scope limits a variable's visibility to that translation unit
Static Local Variable
C++count survives between calls because it is static.
auto Keyword (C++11)
auto tells the compiler to deduce a variable's type from its initializer. It reduces verbosity, especially with complex types like iterators.
auto
auto is not dynamic typing, the type is still fixed at compile time; you just let the compiler figure it out for you.
- auto x = 42; deduces int
- auto y = 3.14; deduces double (not float, use 3.14f for float)
- auto must have an initializer: auto x; is a compile error
- Most useful for long type names: auto it = myVector.begin();
auto Type Deduction
C++The compiler deduces each type from the assigned value.
Knowledge Check
1. What keyword makes a variable's value unchangeable after initialization?
2. Where does a local variable live?
3. What does the auto keyword do in C++11?
4. A static local variable is initialized:
5. Which of these declares and initializes multiple variables in one line?