Definition of a side effect
What you'll learn: You will understand how C distinguishes between the value a calculation produces and the changes it makes to the computer's memory.
More than just a result
In mathematics, when you look at an expression like 5 + 5, the only thing that matters is the result: 10. The numbers don't "do" anything to your notebook; they just represent a value.
In C programming, expressions work a bit differently. Most expressions produce a value, but some also change the state of your program. This change to the environment is called a side effect.
Think of a side effect like a vending machine. When you put in money and press a button, the "result" or value you get is a snack. However, the machine also has a side effect: the stock count for that snack decreases by one. The state of the world has changed.
The main culprits
In C, the most common way to trigger a side effect is through assignment. When you write x = 10, two things happen:
- The expression itself evaluates to the value
10. - As a side effect, the value stored in the variable
xis physically updated in memory.
Other common side effects include using increment/decrement operators (++ and --) or performing Input/Output (like printing to the screen).
Seeing it in code
Consider this example where we use the increment operator. It shows how one line of code can have both a value and a lasting impact on a variable.
#include <stdio.h>
int main() {
int cookies = 5;
int result;
// The expression (cookies++) has a value of 5.
// But it has a SIDE EFFECT: it increases cookies to 6.
result = cookies++;
printf("Value of the expression: %d\n", result); // Output: 5
printf("Side effect on variable: %d\n", cookies); // Output: 6
return 0;
}
In the code above, if C only cared about values, cookies would stay 5 forever. The side effect is the actual "work" of updating the memory address where cookies lives.
Why it matters
Understanding side effects is crucial because it helps you realize that some code doesn't just calculate—it alters. If you use a side-effect-heavy expression twice, the second time might behave differently because the first time already changed the "state of the world."
Key takeaway
A side effect is any change to the program's state (like modifying a variable) that happens during the evaluation of an expression.