Declaring Multiple Variables
Efficient Variable Declaration
C++ allows declaring multiple variables of the same type in a single statement. This can make code more concise and clearer when working with related variables.
Comma-Separated Declaration
You can declare and initialize multiple variables in one line:
int width = 10, height = 20, depth = 30;
double price = 12.99, tax = 1.99, total{}; // total value-initialized to 0.0
char first = 'A', last = 'Z';
Batch Assignment
You can give the same value to several variables in a single expression:
int x, y, z;
x = y = z = 50; // All variables get the value 50
// Equivalent to:
// z = 50;
// y = z;
// x = y;
Safer Initialization
Brace initialization avoids uninitialized variables and narrowing conversions:
int a{}; // 0
int b{42}; // 42
int c = 7; // 7
double unit{12.99}, taxRate{1.99}, total{}; // total == 0.0
Pointers & Qualifiers Pitfalls
Be careful when mixing pointers or qualifiers on one line—the asterisk (*) binds to each declarator, not the type specifier:
int *p, *q; // both pointers to int
int* a, b; // a is int*, b is int (surprising!)
const int cx = 1, cy = 2; // both const
int const* cp1, cp2; // cp1: pointer to const int; cp2: const int (not a pointer!)
auto on Multiple Declarators
Using auto with multiple declarators can be confusing. All declarators must deduce a compatible base type, but each declarator’s *, &, and [] still apply individually.
int i = 42;
auto *p = &i; // p: int*
// Legal but confusing — types differ by declarator form:
auto *p2 = &i, n = 0; // p2: int*, n: int (avoid)
// Error: inconsistent deduction for auto
// auto a = 1, b = 2.5; // one int, one double — ill-formed
Best Practices
When declaring multiple variables:
- Group only related variables together
- Avoid putting too many variables on one line (3–4 maximum is reasonable)
- Use consistent formatting for readability
- Prefer clarity over brevity
// Good example
int red = 255, green = 128, blue = 64;
// Less readable example
int a=1,b=2,c=3,d=4,e=5;