C Multiple Variables
As your programs grow you will need many variables at once. C gives you handy shortcuts for declaring several variables together and for giving them the same value. This page shows the tidy ways to do that.
Declaring Many Variables Together
If several variables share the same type, you can declare them on one line by separating the names with commas. This saves space and keeps related variables grouped.
One type, several variables
#include <stdio.h>
int main() {
int x = 5, y = 10, z = 15;
printf("%d %d %d\n", x, y, z);
return 0;
}Assigning One Value to Many Variables
If you want several variables to start with the same value, you can chain the assignment. C evaluates it from right to left, so the value flows into each variable.
Same value for several variables
#include <stdio.h>
int main() {
int a, b, c;
a = b = c = 0;
printf("%d %d %d\n", a, b, c);
return 0;
}Mixing Types Needs Separate Lines
When your variables are different types, declare each on its own line. This is clearer to read and required by the compiler.
Different types on separate lines
#include <stdio.h>
int main() {
int quantity = 3;
float price = 2.50;
char unit = 'L';
printf("%d %c at %.2f each\n", quantity, unit, price);
return 0;
}- Group same type variables with commas to save space.
- Chain assignments with = to share one starting value.
- Use separate lines when the types differ.
- Give variables descriptive names so the code explains itself.