Variables and operators
Storing values, doing arithmetic, comparing, and the two surprises of integer maths.
Variables
A variable is a named place in memory that holds a value. You create one by stating its type and its name, and you can give it a starting value at the same time.
#include <stdio.h>
int main(void) {
int temperature = 21;
printf("temperature is %d\n", temperature);
temperature = 25; // store a new value
printf("temperature is now %d\n", temperature);
temperature = temperature + 1; // use the old value to make the new one
printf("and now %d\n", temperature);
return 0;
}
The = sign does not mean "equals" as in mathematics. It means "store the value on the right into the variable on the left". That is why temperature = temperature + 1 makes sense. Work out the right side first, then store the result.
Pitfall: Always give a variable a value before you read it. A variable that has never been set holds whatever happened to be in memory.
Types
The type says what kind of value a variable holds and how much memory it takes. You will meet these first.
| Type | Holds | Example |
|---|---|---|
int | Whole numbers, positive or negative | int count = -5; |
unsigned | Whole numbers that are never negative | unsigned total = 40000; |
char | One character | char grade = 'A'; |
bool | true or false | bool ready = true; |
float | Numbers with a fraction | float volts = 3.3f; |
Firmware uses whole numbers almost everywhere. Many small microcontrollers have no hardware for fractions, which makes float slow, so you will mostly work with int and its relatives.
Because the exact size of int depends on the chip, embedded code usually uses types that state their size. uint8_t is an unsigned 8-bit number and int16_t is a signed 16-bit one. You will see these everywhere from the next guides onwards, and they behave just like int.
A name for a value that never changes is written with const.
const int MAX_SPEED = 120; // the compiler will not let anything change this
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 |
% | remainder | 7 % 2 | 1 |
Two of these surprise everyone.
Division of whole numbers throws away the fraction. 7 / 2 is 3, not 3.5. The result is not rounded, it is cut off.
% gives the remainder. 7 % 2 is 1, because 7 is three twos with 1 left over.
#include <stdio.h>
int main(void) {
int total_seconds = 200;
int minutes = total_seconds / 60;
int seconds = total_seconds % 60;
printf("%d seconds is %d min %d s\n", total_seconds, minutes, seconds);
printf("1 / 4 * 100 = %d\n", 1 / 4 * 100);
printf("1 * 100 / 4 = %d\n", 1 * 100 / 4);
return 0;
}
The last two lines show the rule that will save you many times. Multiply first, divide last. 1 / 4 is 0, and 0 times 100 is still 0.
Order of operations
C follows the order you learned at school. Multiplication, division and remainder happen before addition and subtraction. Parentheses come first of all.
#include <stdio.h>
int main(void) {
printf("%d\n", 10 + 20 / 2); // division first, so 10 + 10
printf("%d\n", (10 + 20) / 2); // parentheses first, so 30 / 2
return 0;
}
When you are not sure, add parentheses. They cost nothing and make your intention clear to the next reader.
Shortcuts
Changing a variable based on its own value is so common that C has short forms for it.
| Short form | Same as |
|---|---|
x += 5; | x = x + 5; |
x -= 5; | x = x - 5; |
x *= 2; | x = x * 2; |
x /= 2; | x = x / 2; |
x++; | x = x + 1; |
x--; | x = x - 1; |
Comparing values
A comparison asks a question and produces an answer. In C the answer is a number, 1 for true and 0 for false.
| Operator | Question |
|---|---|
== | are they equal? |
!= | are they different? |
< | is the left one smaller? |
> | is the left one larger? |
<= | smaller or equal? |
>= | larger or equal? |
#include <stdio.h>
int main(void) {
int battery = 15;
printf("battery < 20 is %d\n", battery < 20);
printf("battery == 100 is %d\n", battery == 100);
printf("battery != 0 is %d\n", battery != 0);
return 0;
}
Pitfall: One
=stores a value. Two,==, compares. Writing=where you meant==is the most famous bug in C.
Combining conditions
Three logical operators join questions together.
| Operator | Meaning | True when |
|---|---|---|
&& | and | both sides are true |
|| | or | at least one side is true |
! | not | the thing after it is false |
#include <stdio.h>
int main(void) {
int temperature = 30;
int door_open = 0;
printf("in range: %d\n", temperature >= 10 && temperature <= 40);
printf("alarm: %d\n", temperature > 80 || door_open);
printf("door closed: %d\n", !door_open);
return 0;
}
To test whether a value lies in a range, write two comparisons joined by &&. The mathematical form 10 <= t <= 40 compiles and gives the wrong answer.
Common mistakes
- Expecting
5 / 2to be 2.5. - Dividing before multiplying in a formula.
- Using
=where==was meant. - Reading a variable before giving it a value.
- Writing a range test as
0 <= x <= 10.
Interview question: Why does firmware avoid floating-point numbers where it can?
Answer: Many small microcontrollers have no hardware for floating-point arithmetic. Each operation then becomes a call into a software library, which is slow and adds several kilobytes to the program. Whole-number arithmetic is fast on every chip, so values are stored scaled up instead, for example a temperature in tenths of a degree or a voltage in millivolts.
In the product: a kitchen scale
A scale turns a raw count from its load cell into grams. Every step is variables and integer arithmetic, and the order matters: divide too early and every weight under a kilogram becomes zero.
#include <stdio.h>
int main(void) {
long raw = 25000; // the load cell's count with a bowl of flour on it
long tare = 5000; // the count with nothing on it
long counts_per_kg = 40000; // from the factory calibration
long wrong = (raw - tare) / counts_per_kg * 1000; // divides first: loses everything below 1 kg
long grams = (raw - tare) * 1000 / counts_per_kg; // multiplies first
printf("divide first: %ld g\n", wrong);
printf("multiply first: %ld g\n", grams);
return 0;
}
Build it: grams to ounces
This is step 2 of the module project. The scale is sold in the US too, where recipes use ounces. The chip has no floating-point unit, so the conversion is done with whole numbers.
Lab: Convert between units with integer arithmetic
One ounce is 28.35 g. To keep one decimal place without float, work in tenths of an ounce:
tenths = grams * 1000 / 2835
(1000 / 2835 is the same ratio as 10 / 28.35; multiply first, then divide, or the small numbers round to 0.)
to_tenth_oz(grams)returns the weight in tenths of an ounce, rounded down.show_oz(grams)prints it with one decimal place, such as4.4 ozand a newline. The whole ounces aretenths / 10, and the decimal digit istenths % 10.is_heavier(a_grams, b_grams)returns 1 when the first weight is more than the second, and 0 otherwise.
Going deeper
Interview question: How would you make a kitchen scale's reading steady and accurate to a gram?
Answer: Calibrate with a known weight to get counts per kilogram, store it in non-volatile memory, and tare at power-up and on demand. Average or median-filter the load cell's readings, and only update the display when the reading has been stable for a moment, so the last digit does not flicker. Keep the arithmetic in integers wide enough for the intermediate products, and compensate the load cell's drift with temperature if the accuracy target needs it.
Interview question: Why does 7 / 2 give 3 in C, and how do you get 3.5?
Answer: Both operands are integers, so C performs integer division and discards the fractional part (it truncates towards zero). To get 3.5, make at least one operand floating point, for example 7.0 / 2 or (double)a / b. In firmware, the integer behaviour is often what you want; to round instead of truncate, add half the divisor first: (a + b / 2) / b for positive values.
Interview question: What happens when you store 300 in a uint8_t?
Answer: A uint8_t holds 0 to 255. Converting a larger value to an unsigned type is defined to wrap modulo 256, so 300 becomes 44. The compiler may warn with -Wconversion. Silent truncation like this is a common bug when a computed value is stored in a variable that is too small.
Explain it: In your own words, explain the difference between = and == and why mixing them up is dangerous.
Answer: = is assignment: it stores the value on the right in the variable on the left, and the whole expression has the stored value. == compares two values and gives 1 if they are equal, 0 otherwise. Writing if (x = 5) assigns 5 to x and the condition is always true, so the code runs when it should not and x is overwritten. Compilers warn about it, and some people write constants on the left to make the mistake a compile error.