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.