C Declare Multiple Variables
Declare Multiple Variables
To declare more than one variable of the same type, use a comma-separated list:
Note: All variables must be of the same type. You cannot mix types in the same declaration.
You can also assign the same value to multiple variables at once:
Be careful: int x, y, z = 50; does not give all three variables the value 50. Only z gets it. x and y are declared, but they have no value yet.
Tip: Declaring multiple variables on one line is convenient, but declaring them on separate lines can make your code easier to read.
Swap Two Variables
A common task in programming is to swap the values of two variables.
To do this, you need a third variable that holds one of the values for a moment. It works like swapping the drinks in two glasses: you need an empty third glass to do it.
Example
int a = 5;
int b = 10;
int temp;
// Swap the values of a and b
temp = a;
a = b;
b = temp;
printf("a is %d, b is %d", a, b);
Try it Yourself »
Run the simulation below to see how the values move between the variables:
Code
Output
Variables
Explanation
Why do we need temp? If you only write a = b; and then b = a;, both variables end up as 10. The first line replaces the 5 in a, so it is lost before b can get it.