C Refresher

Operators & Control Flow

Operators allow you to manipulate variables, and control flow allows you to make decisions based on those manipulations.


Operators

C includes all standard math and comparison operators, plus bitwise operators which are critical for configuring hardware registers.

c
1#include <stdint.h>
2#include <stdbool.h>
3
4int main() {
5 int a = 10;
6 int b = 3;
7
8 // Arithmetic
9 int sum = a + b;
10 int diff = a - b;
11 int product = a * b;
12 int quotient = a / b; // integer division — 10/3 = 3
13 int remainder = a % b; // modulo — 10%3 = 1
14
15 // Comparison (returns 0 for false, 1 for true)
16 if (a == b) { /* equal */ }
17 if (a != b) { /* not equal */ }
18 if (a > b) { /* greater than */ }
19 if (a <= b) { /* less than or equal */ }
20
21 // Logical
22 bool flag = false;
23 if (a > 0 && b > 0) { /* both true */ }
24 if (a > 0 || b > 0) { /* at least one true */ }
25 if (!flag) { /* flag is false */ }
26
27 // Bitwise (very common in embedded — setting/clearing register bits)
28 uint8_t reg = 0x00;
29 reg |= (1 << 3); // set bit 3 (OR)
30 reg &= ~(1 << 3); // clear bit 3 (AND NOT)
31 reg ^= (1 << 3); // toggle bit 3 (XOR)
32
33 if (reg & (1 << 3)) {
34 // check if bit 3 is set
35 }
36
37 return 0;
38}

Control Flow

if / else

c
1int sensor_value = 512;
2
3if (sensor_value > 800) {
4 printf("High\n");
5} else if (sensor_value > 200) {
6 printf("Normal\n");
7} else {
8 printf("Low\n");
9}

switch

Best used with enum types for state machines.

c
1typedef enum {
2 MODE_STA,
3 MODE_AP,
4 MODE_STA_AP
5} wifi_mode_t;
6
7wifi_mode_t mode = MODE_STA;
8
9switch (mode) {
10 case MODE_STA:
11 printf("Station mode\n");
12 break;
13 case MODE_AP:
14 printf("Access Point mode\n");
15 break;
16 case MODE_STA_AP:
17 printf("Combined mode\n");
18 break;
19 default:
20 printf("Unknown mode\n");
21 break;
22}

Loops

c
1// 1. FOR loop — used when you know the exact iteration count
2for (int i = 0; i < 10; i++) {
3 printf("i = %d\n", i);
4}
5
6// 2. WHILE loop — used when a condition determines termination
7int retries = 0;
8while (!wifi_connected() && retries < 5) {
9 retry_connect();
10 retries++;
11}
12
13// 3. INFINITE loop — the main pattern in embedded firmware
14while (1) {
15 // Super loop: read sensors, process, act
16 read_sensors();
17 process_data();
18
19 // Always yield the CPU in an RTOS environment!
20 vTaskDelay(pdMS_TO_TICKS(100));
21}
Previous
Variables & Types