Assigning values with =
What you'll learn: How to use the assignment operator to store and update data inside your variables.
The Direction of Data
In mathematics, the equals sign (=) usually means "these two things are the same." However, in C programming, the = symbol is an action. It is called the assignment operator.
Think of a variable as a physical storage box with a label. When you use the = sign, you are picking up a piece of data and placing it inside that box. Because of this, the direction matters immensely: the data always flows from the right side to the left side.
Putting it into Practice
To assign a value, you put the variable name on the left, the assignment operator in the middle, and the value you want to store on the right. You must always end the statement with a semicolon.
int playerScored; // Creating the box
playerScored = 10; // Placing the value 10 into the box
int totalPoints;
totalPoints = playerScored; // Copying the value from one box to another
In the example above, totalPoints = playerScored doesn’t link the two variables forever. It simply looks at what is currently inside playerScored (which is 10), makes a copy of it, and drops that copy into totalPoints.
Overwriting the Old
One of the most important things to remember is that a variable can only hold one value at a time. If you assign a new value to a variable that already has something in it, the old value is discarded and replaced instantly. It’s like recorded over an old VHS tape; once the new data is written, the old data is gone forever.
int heatLevel;
heatLevel = 5; // The box now holds 5
heatLevel = 92; // The 5 is tossed out; the box now holds 92
Always read the = sign as "gets" or "becomes." Instead of saying "heatLevel equals 92," say "heatLevel gets the value 92." This mental habit will help you avoid confusion when you start writing more complex code.
Key takeaway
The = operator takes the value from the right side and stores it in the variable on the left, replacing whatever was there before.