← Back to C Course | Chapter 1: Introduction & Basics | Lesson 19 of 21

C Multiple Variables

C lets several variables of the same type be declared, and optionally initialized, in a single comma-separated statement, and even supports chained assignment across multiple variables.

Declaring Multiple Variables of the Same Type

Multiple variables of the same type can be declared in a single statement by separating their names with commas after one type keyword, avoiding the repetition of writing the type multiple times.

Example: Declaring Multiple Variables of the Same Type

c
#include <stdio.h>
int main() {
	int a, b, c;
	a = 1; b = 2; c = 3;
	printf("%d %d %d", a, b, c);
	return 0;
}

Declaring and Initializing Together

Each variable in a comma-separated declaration can also be given its own initial value, combining declaration and initialization for several variables of the same type in one line.

Example: Declaring and Initializing Together

c
#include <stdio.h>
int main() {
	int a = 1, b = 2, c = 3;
	printf("%d %d %d", a, b, c);
	return 0;
}

Multiple Variables of Different Types

A single declaration statement can only introduce variables of one specific type, so variables of different types, like an int and a float, must always be declared in separate statements.

Example: Multiple Variables of Different Types

c
#include <stdio.h>
int main() {
	int age = 25;
	float height = 5.9f;
	printf("%d %.1f", age, height);
	return 0;
}

Multiple Assignment in One Statement

C allows chained assignment, such as x = y = z = 10, which evaluates right to left, assigning the same value to multiple variables in a single expression statement.

Example: Multiple Assignment in One Statement

c
#include <stdio.h>
int main() {
	int x, y, z;
	x = y = z = 10;
	printf("%d %d %d", x, y, z);
	return 0;
}

Readability Considerations

While declaring many variables on one line saves space, grouping only closely related variables together and keeping unrelated ones on separate lines generally keeps code easier to read and maintain.

Example: Readability Considerations

c
#include <stdio.h>
int main() {
	int width = 10, height = 20;
	float price = 9.99f;
	printf("%d %d %.2f", width, height, price);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.