Loading lessons...
Multiple Variables in One Line
Multiple Variables in One Line
Making one variable is great; making ten is where it gets interesting. C has a shortcut to declare several at once.
Declaring many in one line
You can create several variables of the same type in a single statement, separating them with commas:
int x = 5, y = 6, z = 50;
That one line creates three integer variables: x holding 5, y holding 6, and z holding 50.
The general pattern
type a = value1, b = value2, c = value3;
The type is written once, at the front, and applies to all of them.
Readable style
A one-liner is compact, but a long line is hard to read. Many programmers spread the same declaration over several lines:
int x = 5,
y = 6,
z = 50;
Same result, easier to scan.
One catch: no shared types
The shortcut only works when the variables share the same type:
int age = 10;
double price = 2.50;
TL;DR
- Declare many same-type variables in one line:
int x = 5, y = 6, z = 50;. - The type is written once and applies to all.
- Break the line up for readability.
- Different types need separate statements.