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>34int main() {5 int a = 10;6 int b = 3;78 // Arithmetic9 int sum = a + b;10 int diff = a - b;11 int product = a * b;12 int quotient = a / b; // integer division — 10/3 = 313 int remainder = a % b; // modulo — 10%3 = 11415 // 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 */ }2021 // Logical22 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 */ }2627 // 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 }3637 return 0;38}Control Flow
if / else
c
1int sensor_value = 512;23if (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_AP5} wifi_mode_t;67wifi_mode_t mode = MODE_STA;89switch (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 count2for (int i = 0; i < 10; i++) {3 printf("i = %d\n", i);4}56// 2. WHILE loop — used when a condition determines termination7int retries = 0;8while (!wifi_connected() && retries < 5) {9 retry_connect();10 retries++;11}1213// 3. INFINITE loop — the main pattern in embedded firmware14while (1) {15 // Super loop: read sensors, process, act16 read_sensors();17 process_data();18 19 // Always yield the CPU in an RTOS environment!20 vTaskDelay(pdMS_TO_TICKS(100));21}
