Simple assignment =
What you'll learn: How to use the equals sign to store data in a variable.
In C, the = sign doesn’t mean "these two things are currently equal," like it does in a math equation. Instead, think of it as an action. It is an instruction to take a piece of information and pour it into a container.
The Direction of Flow
The most important rule of the assignment operator is the direction of travel. Information always flows from the right to the left.
Imagine you have a cardboard box labeled score. If you want to put the number 10 inside that box, you write score = 10;. The computer looks at the right side first, sees the value 10, and then shoves it into the variable named on the left. Because of this, the left side must always be a container (a variable), while the right side can be a raw number, another variable, or even a calculation.
Overwriting Values
A variable can only hold one thing at a time. When you use the = operator on a variable that already contains data, the old data is tossed out and replaced by the new data. It’s like painting a wall; if the wall is currently blue and you paint it red, the blue is gone forever.
int goldCoins;
// Assign the value 50 to goldCoins
goldCoins = 50;
// The old 50 is discarded, and goldCoins now holds 100
goldCoins = 100;
// We can even use the value of one variable to set another
int bankVault;
bankVault = goldCoins;
Common Confusion
In daily life, we might say "5 equals x" or "x equals 5" and mean the same thing. In C, you cannot say 5 = x;. If you try to put a variable into a raw number, the computer will get confused because the number 5 isn't a container—it’s just a value. Always put the "box" on the left and the "content" on the right.
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.