Variables Basics
Lesson outline
Introduction to Variables
Variables are fundamental building blocks in C++ that allow you to store and manipulate data. They act as named containers that hold values which can change during program execution.
Each variable in C++ has a specific type that determines the size and layout of memory, the range of values it can store, and the operations that can be applied to it.
Basic Variable Types
C++ provides several fundamental types for variables:
Variable Declaration and Initialization
Variables can be declared and initialized in different ways. Prefer initializing upon declaration:
Constants and Type Inference
Use const for values that should not change and constexpr for compile-time constants when possible. auto lets the compiler deduce the type from the initializer.
Default Initialization vs Zero-Initialization
Local (block-scope) fundamental variables are not zero-initialized by default. Objects with static storage duration (e.g., globals, static variables) are zero-initialized.
Variable Usage and Scope
Variables can be used in calculations and output statements. Their values can also be reassigned during program execution: