Course contentsShow
← C
Lesson 76 of 1,2192. Variables and TypesFree lesson

Multiple declarations in one line

Multiple declarations in one line

What you'll learn: How to group similar variables together using a single type keyword to keep your code organized and concise.

The "Same Aisle" principle

Imagine you are at a grocery store. If you need to buy an apple, a banana, and a cherry, you don’t drive to three different stores. You go to the produce section because all three items belong to the same category.

In C, variables often travel in packs. If you are building a game, you might need an x coordinate and a y coordinate. Since both of these are integers, C allows you to "shop" for them in one go. Instead of writing a new line for every single variable, you can list them side-by-side, separated by commas.

How to bundle variables

When you declare multiple variables on one line, you state the data type once, followed by your chosen names separated by commas, and ending with a single semicolon.

Think of the type (like int) as a label on a storage bin. By using a comma-separated list, you are telling the computer, "Hey, I need three different bins, and I want all of them to be labeled 'Integer'."

#include <stdio.h>

int main() {
    // Declaring three integers at once
    int playerHealth, enemyHealth, bossHealth;

    // You can even assign values (initialize) in a bundle
    int x = 10, y = 20, z = 30;

    // You can even mix and match: some with values, some without
    int gold = 100, silver, bronze = 5;

    return 0;
}

When to use this (and when to avoid it)

Bundling is great for variables that are logically related. If you have three variables representing the dimensions of a box (length, width, height), putting them on one line makes it clear they belong together. It makes your code look cleaner and less "vertical."

However, avoid overdoing it. If you try to cram ten different, unrelated variables onto one line, your code becomes a wall of text that is hard to read. A good rule of thumb is: if the variables serve the same purpose, keep them together; if they do different jobs, give them their own space.

Key takeaway

Use commas to declare multiple variables of the same type in a single statement to keep your code organized.