Sub topic 6
Operators and expressions
This chapter assumes you can write a sketch with setup() and loop(), declare variables of the basic types (int, byte, long, float, bool), and print to the Serial Monitor. Examples assume an Arduino Uno, where int is 16 bits. Where a result depends on that, the text says so.
What an expression is
An operator is a symbol that acts on values. An expression is any combination of values, variables, operators, and function calls that produces a single value. 3 + 4, ledPin, analogRead(A0) > 512, and digitalRead(2) == HIGH are all expressions. The compiler works out the value and its type, then uses the result in an assignment, a condition, or a function argument.
Most operator bugs come from two things. One is the type the compiler picks for a result. The other is the order in which it evaluates the parts.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` `-` `*` | Add, subtract, multiply | `6 * 7` | `42` |
| `/` | Divide | `7 / 2` | `3` (integers) |
| `%` | Remainder (modulo) | `7 % 2` | `1` |
Integer division truncates
If both sides of / are integers, the result is an integer and the fraction is discarded. The type of the destination does not matter. The division happens first.
void setup() {
Serial.begin(9600);
int a = 7 / 2; // 3
float b = 7 / 2; // 3.00: the division was already done as integers
float c = 7 / 2.0; // 3.50: one float operand makes it a float division
int d = 7 % 2; // 1
Serial.println(a);
Serial.println(b);
Serial.println(c);
Serial.println(d);
}
void loop() {
}The line float b = 7 / 2; is the classic surprise. Make at least one operand a float (2.0, or a cast such as (float)total / count) before the division happens.
Modulo for wrapping
% gives the remainder, which makes it a good tool for cycling through a range. index = (index + 1) % 4; counts 0, 1, 2, 3, 0, 1, and so on. It is also the usual way to test for even numbers (n % 2 == 0) or to act on every tenth pass (count % 10 == 0). % works on integers only. Using it on a float is a compile error.
Integer overflow and type promotion
Each integer type has a fixed range. When a result does not fit, it wraps around and no error is reported.
| Type (Uno) | Size | Range |
|---|---|---|
| `byte` | 8 bits | 0 to 255 |
| `int` | 16 bits | -32768 to 32767 |
| `unsigned int` | 16 bits | 0 to 65535 |
| `long` | 32 bits | about -2.1 billion to 2.1 billion |
| `unsigned long` | 32 bits | 0 to about 4.29 billion |
void setup() {
Serial.begin(9600);
byte b = 250;
b += 10; // 260 does not fit: wraps to 4
Serial.println(b);
int big = 30000;
big = big + 10000; // 40000 does not fit in 16 bits: wraps to -25536
Serial.println(big);
long wrong = 60 * 1000; // both literals are int, so the multiply overflows
long right = 60L * 1000; // 60L is a long, so the multiply is done in 32 bits
Serial.println(wrong); // -5536
Serial.println(right); // 60000
}
void loop() {
}The compiler evaluates the right-hand side of long wrong = 60 * 1000; using the types of the operands. Both are int, so the product is computed as a 16-bit int and wraps before it is stored in the long. The suffix L makes a literal long, and UL makes it unsigned long. When an expression mixes types, the smaller type is promoted to the larger one. Promotion only applies to a single operation. It does not rescue an earlier operation that already overflowed.
Scaling a sensor reading
analogRead() returns 0 to 1023. To convert it to a percentage, order matters:
int reading = 800;
int bad = reading / 1023 * 100; // 0: reading / 1023 is 0 in integer math
int good = reading * 100L / 1023; // 78: multiply first, in 32 bits, then divideThe 100L matters because 800 * 100 is 80000, which overflows a 16-bit int. Multiply first to keep precision, but use a wide enough type for the intermediate result.
Assignment and compound operators
= stores a value. It does not test equality. Compound operators combine an operation and an assignment.
| Operator | Same as |
|---|---|
| `x += 5` | `x = x + 5` |
| `x -= 5` | `x = x - 5` |
| `x *= 2` | `x = x * 2` |
| `x /= 2` | `x = x / 2` |
| `x %= 10` | `x = x % 10` |
| `x++` / `++x` | `x = x + 1` |
| `x--` / `--x` | `x = x - 1` |
The prefix form (++x) increments and then yields the new value. The postfix form (x++) yields the old value and then increments. On their own line the two behave the same. Do not use the incremented variable twice in one expression, as in a[i] = i++;, because the result is unreliable.
Comparison operators
Comparison operators yield a bool: true (1) or false (0).
| Operator | Meaning |
|---|---|
| `==` | equal to |
| `!=` | not equal to |
| `<` `>` | less than, greater than |
| `<=` `>=` | less than or equal, greater than or equal |
The = versus == mistake
if (buttonState = HIGH) { // assigns HIGH, then tests the result: always true
// runs every time
}
if (buttonState == HIGH) { // compares
// runs only when the button reads HIGH
}The first version compiles. It overwrites buttonState and the branch always runs. Some programmers write the constant first (HIGH == buttonState), because a typo such as HIGH = buttonState then fails to compile.
Comparing floats
Floats cannot represent most decimal fractions exactly, so == on computed floats is unreliable. Compare against a tolerance instead:
float target = 0.3;
float sum = 0.1 + 0.2;
bool close = abs(sum - target) < 0.0001; // trueLogical operators
| Operator | Meaning | True when | Column | Column |
|---|---|---|---|---|
| `&&` | AND | both sides are true | ||
| `\ | \ | ` | OR | at least one side is true |
| `!` | NOT | the operand is false |
Logical operators use short-circuit evaluation. For a && b, if a is false then b is never evaluated. For a || b, if a is true then b is skipped. You can use this to guard an operation:
if (count > 0 && total / count > 100) {
// total / count only runs when count is not zero
}Any non-zero value counts as true in a condition. That is why && and the bitwise & (next section) differ: 3 && 4 is true, while 3 & 4 is 0, which is false.
Bitwise operators
Bitwise operators work on the individual bits of integers. They are common on microcontrollers for packing several on/off flags into one byte and for working with hardware registers.
| Operator | Meaning | Example (8 bits) | Result | Column | Column |
|---|---|---|---|---|---|
| `&` | AND | `0b1100 & 0b1010` | `0b1000` | ||
| `\ | ` | OR | `0b1100 \ | 0b1010` | `0b1110` |
| `^` | XOR | `0b1100 ^ 0b1010` | `0b0110` | ||
| `~` | NOT (invert) | `~0b00001111` | `0b11110000` | ||
| `<<` | shift left | `1 << 3` | `0b1000` | ||
| `>>` | shift right | `0b1000 >> 3` | `1` |
A common pattern is to use a shifted 1 as a mask for one bit:
byte flags = 0;
void setup() {
Serial.begin(9600);
flags |= (1 << 2); // set bit 2
flags |= (1 << 0); // set bit 0
flags &= ~(1 << 0); // clear bit 0
flags ^= (1 << 5); // toggle bit 5
bool bit2Set = flags & (1 << 2);
Serial.println(flags, BIN); // prints 100100
Serial.println(bit2Set); // prints 1
}
void loop() {
}Arduino also provides bitRead(), bitSet(), bitClear(), and bitWrite(), which express the same operations by name. Shifting left by one doubles a value and shifting right by one halves it, but only for unsigned values or non-negative signed ones. Shifting a 16-bit int by 16 or more bits is undefined, so use 1UL << n for bit positions above 14.
The conditional (ternary) operator
condition ? valueIfTrue : valueIfFalse is an expression that picks one of two values. It is a compact form of a simple if/else:
digitalWrite(ledPin, ledOn ? HIGH : LOW);
const char *label = (reading > 512) ? "high" : "low";Use it for short choices. When either branch needs more than one statement, an if/else is easier to read.
Precedence and associativity
When an expression has several operators, precedence decides which is applied first. Associativity decides the order among operators of equal precedence. This table lists the groups you use most, from highest precedence to lowest:
| Level | Operators | Column | Column |
|---|---|---|---|
| 1 | `++` `--` (postfix), function call `()`, `[]` | ||
| 2 | `!` `~` unary `-` prefix `++` `--`, casts | ||
| 3 | `*` `/` `%` | ||
| 4 | `+` `-` | ||
| 5 | `<<` `>>` | ||
| 6 | `<` `<=` `>` `>=` | ||
| 7 | `==` `!=` | ||
| 8 | `&` | ||
| 9 | `^` | ||
| 10 | `\ | ` | |
| 11 | `&&` | ||
| 12 | `\ | \ | ` |
| 13 | `?:` and assignments (`=`, `+=`, and so on) |
Bitwise & ranks below ==. This catches many people:
if (flags & 0x04 == 0x04) { // parsed as flags & (0x04 == 0x04), that is flags & 1
}
if ((flags & 0x04) == 0x04) { // intended meaning
}Add parentheses whenever you mix bitwise, comparison, and logical operators. They cost nothing at run time and show your intent.
Common errors at a glance
- Writing
=where==was intended in a condition. - Dividing integers and expecting a fraction.
- Overflowing an intermediate result because every literal in it is an
int. - Forgetting parentheses around
&or|inside comparisons. - Using
&or|where&&or||was meant, or the reverse. - Comparing computed floats with
==.
Exercise
On an Uno, what does long total = 200 * 200; store in total, and how do you fix it so it stores 40000?
Show answer
Both literals are 16-bit int, so 200 * 200 is computed as an int. The product 40000 exceeds 32767 and wraps to -25536 before it is stored in the long. Making one literal a long, as in 200L * 200, forces the multiplication to run in 32 bits and stores 40000.
Exercise
Rewrite if (mode & 0x03 == 0x01) so it tests whether the lowest two bits of mode equal 01. Explain why the original does not do that.
Show answer
Write if ((mode & 0x03) == 0x01). Without parentheses, == has higher precedence than &, so the original is parsed as mode & (0x03 == 0x01), which is mode & 1. That tests only whether bit 0 is set and ignores bit 1.