EMZETT.
Login

Multiple Variables (Declaring Multiple Variables)

In short: The ability to create several variables of the same type on a single line, instead of writing a separate line for each — e.g. int a, b, c; instead of three individual declarations.

In more detail: This saves space especially for closely related variables and makes their relationship clear at a glance (e.g. x and y coordinates). With too many or content-wise different variables on one line, readability quickly suffers, though — separate lines with descriptive names are then usually the better choice.

In Depth

int a, b, c;              // three variables, no value yet
int x = 0, y = 0;         // three variables, initialized directly

An important detail that causes confusion in several languages (e.g. Java, C): for int* a, b; in C, ONLY a is a pointer, b, by contrast, is a normal int — the * syntactically only refers to the immediately following variable, not the whole line. Anyone who doesn’t know this often wrongly expects both variables to get the same type addition.

Besides multiple declaration of the same type, some modern languages additionally offer destructuring — extracting several variables in one line from an existing structure (array, object), instead of independently declaring them anew:

const [x, y] = [10, 20];              // from an array
const { name, age } = person;       // from an object

This is conceptually related but technically something different from pure multiple declaration of variables of the same type — here, values are “unpacked” from an existing source, instead of being independently newly assigned.

Practical rule of thumb: multiple declaration on one line is worthwhile especially for 2-3 clearly related values of the same type (coordinates, counter pairs) — once the variables have little to do with each other in content or need different types, the loss of readability clearly outweighs the space savings.

See also: Declaring Variables