C Variable Values
Change Variable Values
If you assign a new value to an existing variable, the new value will replace the old one:
Note: This is normal and expected. Variables are meant to change while a program runs.
You can also assign the value of one variable to another:
Example
int myNum = 15;
int myOtherNum = 23;
// Assign the value of myOtherNum (23) to myNum
myNum = myOtherNum;
// myNum is now 23 (was 15)
printf("%d", myNum);
Try it Yourself »
You can even copy values into variables that were declared earlier without a value:
Example
// Create a variable and assign a value
int myNum = 15;
// Declare a variable without assigning a value
int myOtherNum;
// Copy the value from myNum
myOtherNum = myNum;
// myOtherNum is now 15
printf("%d", myOtherNum);
Try it Yourself »
Add Variables Together
You can use mathematical operators to work with variables.
For example, to add one variable to another, use the + operator:
You can also update a variable using its current value:
Tip: Writing x = x + 1 means "take the current value of x and add 1 to it".
Note: You will learn much more about operators in a later chapter.
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.