Multiple Variables in C
Declaring Multiple Variables
C allows declaring multiple variables of the same type in one line, separated by commas.
This reduces repetition and is common for related values.
#include <stdio.h>
int main(void) {
int a = 1, b = 2, c = 3;
printf("a=%d b=%d c=%d", a, b, c);
return 0;
}
a=1 b=2 c=3
Declaration Without Initialization
You can declare variables first, then assign values later.
Uninitialized variables contain unpredictable garbage values, so initialization is recommended.
#include <stdio.h>
int main(void) {
int x, y; // declared but uninitialized (indeterminate values)
x = 5; // assign later
y = 10;
printf("x=%d y=%d", x, y);
return 0;
}
x=5 y=10
Mixing Initialization
Some variables can be initialized, while others are left uninitialized in the same line.
Example: int x = 10, y, z = 20;
#include <stdio.h>
int main(void) {
int x = 10, y, z = 20; // y is indeterminate until assigned
y = 15;
printf("x=%d y=%d z=%d", x, y, z);
return 0;
}
x=10 y=15 z=20
Pointers & Qualifiers with Multiple Declarations
Be careful when declaring multiple pointers: the asterisk binds to each declarator, not the type keyword.
Qualifiers (like const) also apply per declarator depending on placement.
#include <stdio.h>
int main(void) {
int *p, *q; // both p and q are int pointers
int *r, s; // r is pointer to int, s is plain int
const int a = 3, b = 4; // both are const int
int value = 42;
p = &value; // ok
q = p; // ok
s = value; // ok (s is an int)
printf("*p=%d *q=%d s=%d", *p, *q, s);
return 0;
}
*p=42 *q=42 s=42
Same Statement Must Use One Type
A single declaration statement can only declare variables of one base type. You cannot mix different types in the same comma-separated declaration.
Write separate declarations when the types differ.
#include <stdio.h>
int main(void) {
int count = 10; // ok
double avg = 2.5; // ok
// int count = 10, double avg = 2.5; // ❌ not allowed: mixed types in one declaration
printf("count=%d avg=%.1f", count, avg);
return 0;
}
count=10 avg=2.5
Best Practices
• Keep declarations readable: consider one-per-line when initializers are complex.
• Avoid relying on the order of initialization within a single multi-variable declaration—prefer simple, independent initializers or separate lines.
• Initialize variables as close to first use as practical (C99+ allows mixed declarations and code).
• Prefer separate lines for multiple pointer declarations to avoid mistakes.
• Don’t confuse commas in declarations with the comma operator in expressions—they are different.