C++ Variables Basics
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:
#include <string>
int age = 25; // Integer (whole number)
double price = 9.99; // Floating-point number
char grade = 'A'; // Single character
std::string name = "Alice"; // Text (sequence of characters)
bool isActive = true; // Boolean (true/false)
Variable Declaration and Initialization
Variables can be declared and initialized in different ways. Prefer initializing upon declaration:
// Declaration with initialization (copy initialization)
int count = 10;
// Declaration followed by assignment
int score; // uninitialized (indeterminate value)
score = 100; // now assigned
// Multiple declarations in one statement (ok but can hurt readability)
int x = 5, y = 10, z = 15;
// Direct initialization
int n(42);
// List initialization (prevents narrowing)
double d1{3.5}; // ok
// int narrowed{3.5}; // error: narrowing conversion
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.
#include <string>
const double TaxRate = 0.07; // read-only at runtime
constexpr int BufferSize = 1024; // compile-time constant
auto total = 1 + 2.5; // deduces double
auto label = std::string{"Item"}; // deduces std::string
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.
int globalCounter; // zero-initialized to 0
int main() {
int localCounter; // indeterminate value
static int hits; // zero-initialized to 0
(void)hits; // suppress unused warning
// Use localCounter only after assigning a value
return 0;
}
Variable Usage and Scope
Variables can be used in calculations and output statements. Their values can also be reassigned during program execution:
#include <iostream>
int main() {
int apples = 5;
int oranges = 3;
std::cout << "Total fruits: " << (apples + oranges) << '\n';
apples = 8; // Changing variable value
std::cout << "Now we have " << apples << " apples";
return 0;
}
Total fruits: 8 Now we have 8 apples