Lesson 31: Using - Subtraction Arithmetic Operator
Learn how - subtracts values, how it differs from -=, and how to avoid common subtraction mistakes in Arduino code.
Progress indicator
Lesson 31 of 57
Learning Objectives
- Understand what the subtraction operator (-) does.
- Use - with variables, constants, and expressions.
- Apply subtraction with int, long, and float values.
- Understand - vs -= and when to use each.
- Avoid underflow, overflow, and common subtraction mistakes.
Concept Explanation
What is the Subtraction Operator (-)
The - operator subtracts the right value from the left value.
Arduino code uses subtraction for countdowns, offsets, thresholds, and remaining time.
Subtraction Operator Syntax
result = valueA - valueB;
remaining = total - used;
delta = current - previous;How - Works
- Read left operand value.
- Read right operand value.
- Compute left minus right.
- Store or use the result in the current statement.
Result type depends on operands. For example, float - int gives a float result.
Subtracting Variables and Constants
You can subtract variable - variable, variable - constant, or constant - variable.
int total = 1000;
int used = 250;
int remaining = total - used;- with Different Data Types
int - intreturns int.long - intusually returns long.float - intreturns float.- Large negative or positive results can overflow if type is too small.
| Expression | Output Type | Example Result |
|---|---|---|
int - int | int | 700 - 200 = 500 |
long - int | long | 5000L - 500 = 4500 |
float - float | float | 3.3 - 0.4 = 2.9 |
- vs -= (Comparison)
a = a - b;anda -= b;do the same update.-=is shorter for repeated subtraction in loops.- Use
-for new expressions,-=for in-place updates.
When to Use -
- Countdown timers and remaining budget calculations
- Threshold checks (
current - baseline) - Offset correction for sensor values
- Delta calculations between two readings
Underflow and Wrap-Around
With unsigned values, subtracting a larger number from a smaller one can wrap to a very large positive value.
unsigned int count = 10;
count = count - 20; // wraps on many boardsUse signed types when negatives are valid, or add safety checks before subtracting.
Example Code
This example computes a reduced blink delay and decreases a running time budget with -=.
int ledPin = 2;
int baseDelay = 700;
int reduction = 200;
int blinkDelay = 0;
long totalBudgetMs = 5000;
float targetVoltage = 3.3;
float dropVoltage = 0.4;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
blinkDelay = baseDelay - reduction;
float remainingVoltage = targetVoltage - dropVoltage;
digitalWrite(ledPin, HIGH);
delay(blinkDelay);
digitalWrite(ledPin, LOW);
delay(blinkDelay);
totalBudgetMs -= blinkDelay;
Serial.print("blinkDelay = ");
Serial.println(blinkDelay);
Serial.print("remainingVoltage = ");
Serial.println(remainingVoltage);
Serial.print("totalBudgetMs = ");
Serial.println(totalBudgetMs);
}Example Code Explanation
baseDelayandreductiondefine original delay and subtract amount.blinkDelay = baseDelay - reductioncomputes the new delay each cycle.targetVoltage - dropVoltagegives remaining voltage as a float.- LED blinks ON then OFF using the computed shorter delay value.
totalBudgetMs -= blinkDelayreduces remaining time budget every loop.Serial.printlines confirm each subtraction output during runtime.
Real-life analogy
Think of a mobile data pack: you start with a total balance, and each activity subtracts from that balance. The remaining value is tracked after every use.
What Happens Inside
- Compiler prepares subtraction instructions.
- CPU reads operands into internal registers.
- ALU performs binary subtraction.
- Result and status flags (borrow/overflow related) are updated.
- Destination variable receives the computed value.
- Next program line runs with the new updated value.
Common Mistakes with -
- Subtracting larger from smaller in unsigned types and getting wrap-around values.
- Using a type too small for negative results.
- Writing
x =- 5instead ofx -= 5. - Using subtraction result directly in
delay()without ensuring it is positive.
Best Practices for -
- Pick signed types when negative results are possible.
- Use
-=for repeated subtraction updates in loops. - Print intermediate subtraction results during debugging.
- Clamp values when needed to avoid invalid negative delays or ranges.
- Use guard conditions before subtracting from unsigned counters.
Practice Task
- Change
reductionfrom 200 to 300 and observe newblinkDelay. - Add a safety check so
blinkDelaynever goes below 100 ms. - Create a new variable
int remainingCycles = 20 - 3;and print it. - Replace one
totalBudgetMs -= blinkDelay;withtotalBudgetMs = totalBudgetMs - blinkDelay;and compare.
Try it now
Open the simulator workspace and observe subtraction results step by step.