Lesson 25 +10 XP

Multiple Variables

Multiple Variables

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. Each name still gets its own value.

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. Style is about the humans reading the code - the compiler treats both identically.

One catch: no shared types

The shortcut only works when the variables share the same type. If you need an int and a double, you need two separate statements:

int age = 10;
double price = 2.50;

A warning about mixed initialization

Each variable in a comma list gets its own value - there is no "sharing". Don't assume int x = 5, y; makes y 5 too; it doesn't. y is just uninitialized.

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; the compiler sees no difference.
  • Different types need separate statements.
  • Each variable holds its own value - none are "shared".