Module 0 · Lesson 3 of 12

C toolchain: compile, run, types, operators, control flow

Compile and run your first C programs, master types, operators, precedence and control flow, and read compiler diagnostics like a systems engineer.

  • Beginner to advanced
  • 26 min read
  • 45 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container) with gcc and binutils installed; a text editor

By the end you can 7 objectives
  • Trace the four translation stages a C program passes through and name the sub-programs gcc runs for each.
  • Explain how main's return value becomes the process exit status and inspect it with echo $?.
  • Compile with -Wall -Wextra, distinguish errors from warnings, and read the file, line and column in each diagnostic.
  • Choose the right integer and floating-point type for a value and use sizeof with the limits.h and float.h macros.
  • Apply arithmetic, comparison, logical and increment operators according to C's precedence and associativity rules.
  • Write if/else, switch, while, do-while and for control flow, including break and continue.
  • Use printf and scanf with the correct format specifier and describe why mixing signed and unsigned values is dangerous.
Read the lesson below; the video will appear here when published.
01

Why C, and the shape of a C program

3 min read

becomes through a program called the compiler. That distance, or rather the lack of it, is the whole point of C.

Why does this program teach C first, before the Linux administration and system programming modules? Because on an embedded target, C is the language everything else is written in. The Linux kernel is C. The bootloader that starts your Raspberry Pi is C. Device drivers are C. The hot path of any firmware is C. C gives you three things a higher-level language cannot promise: predictable timing, a tiny footprint, and direct access to memory and registers. A Python program needs a whole interpreter resident in flash before it prints one character; a C program is a few kilobytes of machine code that runs on a 64 KB microcontroller with no operating system at all. That is why, even in a world of Rust and C++, every systems engineer still reads and writes C.

A first program makes all of this concrete:

c
#include <stdio.h>

int main(void)
{
    printf("hello, world\n");
    return 0;
}

Take it apart line by line. #include <stdio.h> copies the declarations for printf into this file before compilation. int main(void) defines main, the function the operating system runs first. The braces { } wrap its body. printf(...) is a function call, ended by a semicolon, which prints the string and moves to a new line because of the \n. return 0; hands a status back to whoever ran the program. Anything between /* and */, or after //, is a comment the compiler ignores, meant for the human who returns to this file months later.

To build and run it you reuse the loop from the previous lesson:

bash
gcc -o hello hello.c
./hello

gcc -o hello hello.c runs the whole pipeline and writes an executable named hello; ./hello runs it. The ./ tells the shell the program is in the current directory. Everything that follows in this lesson is about what happens inside that one command, and about the language you will type between the braces.

From source to processsource.ctext youwritecompilegcctranslatesitexecutablemachinecode fileprocessrunning inmemorysource.ctext youwritecompilegcctranslatesitexecutablemachinecode fileprocessrunning inmemory
A C source file becomes machine code, which the operating system then loads as a running process.
Compile and run your first C program
learner@embeddex:~/lab$ # compile hello.c into an executable named hello
learner@embeddex:~/lab$ gcc -o hello hello.c
learner@embeddex:~/lab$ # ./ means in this directory
learner@embeddex:~/lab$ ./hello
hello, world
learner@embeddex:~/lab$ # main returned 0, and that became the exit status
learner@embeddex:~/lab$ echo $?
0
02

The four translation stages

4 min read

The previous lesson named the four stages. This one opens each up, because the moment a build goes wrong, you want to know which machine on the line is complaining. A single source file passes through preprocess, compile, assemble and link, and the same four stages run whether the target is your laptop or an ARM board.

Step by stepThe four stages and the file each produces
  1. Preprocess: the preprocessor expands #include and #define into a single stream of pure C, the .

  2. Compile: the compiler proper, the cc1 program, translates that C into assembly language for the target CPU.

  3. Assemble: the as assembler turns the assembly into an object file of machine code plus symbols.

  4. Link: the linker combines your object file with the C library and startup code into one executable.

You can stop the pipeline at any stage and read the intermediate file, which is the fastest way to understand each one. -E stops after preprocessing, -S after compiling to assembly, -c after assembling to an object file, and -o names any output:

bash
gcc -E hello.c -o hello.i   # preprocessed C
gcc -S hello.c -o hello.s   # assembly
gcc -c hello.c -o hello.o   # object file
gcc -o hello hello.c        # link everything into an executable

Open hello.i and you will find thousands of lines: your four lines at the very bottom, and above them the entire contents of stdio.h expanded in place. Open hello.s and you will find the assembly the compiler chose. On x86-64 it looks something like this, the well-known standard form for a trivial function (your compiler and flags will produce a variant):

asm
main:
        pushq   %rbp
        movq    %rsp, %rbp
        leaq    .LC0(%rip), %rdi
        call    printf
        movl    $0, %eax
        popq    %rbp
        ret

The string lives in a read-only section labelled .LC0, call printf invokes the library, and movl $0, %eax loads the return value. Assembly is one text line per machine instruction, which is why reading it teaches you more about the CPU than any amount of prose.

Run gcc -v to watch the driver confess the sub-programs it runs. Typical output (yours will differ):

shell
/usr/lib/gcc/x86_64-linux-gnu/<version>/cc1 hello.c -o /tmp/ccXXXX.s
as --64 -o /tmp/ccYYYY.o /tmp/ccXXXX.s
/usr/lib/gcc/x86_64-linux-gnu/<version>/collect2 ... -o hello /tmp/ccYYYY.o ...

The Target: line names the triple, which for embedded work is the whole story. A compiler whose triple begins x86_64 builds for your laptop; aarch64-linux-gnu-gcc runs the same four stages but emits ARM instructions for the Pi. Building for a CPU other than the one you run on is cross-compilation, and it returns in every module that follows.

Going deeperWhat the driver actually runs

The cc1 binary sits under /usr/lib/gcc/<triple>/<version>/, not on your PATH, which is why you never call it directly. In modern gcc the preprocessor is folded into cc1, although a standalone cpp still exists for compatibility. collect2 is a wrapper that locates the startup objects and the C library before handing off to ld. One of those startup objects is crt1.o, which contains _start, the real entry point the kernel jumps to; _start arranges the runtime and calls your main. When a build fails with a message mentioning ld or collect2, the linker cannot find a symbol, which almost always means a missing library, a misspelt function name, or a source file you forgot to list on the command line.

The four translation stagespreprocessexpandincludes,-EcompileC toassembly,-Sassembleassembly toobject, -clinkjoinlibraries,-opreprocessexpandincludes,-EcompileC toassembly,-Sassembleassembly toobject, -clinkjoinlibraries,-o
The four stages from hello.c to an executable, with the tool and the file extension of each stage.
Stop the compiler at each stage
learner@embeddex:~/lab$ # -S stops after compiling to assembly
learner@embeddex:~/lab$ gcc -S hello.c -o hello.s
learner@embeddex:~/lab$ # one text line per machine instruction
learner@embeddex:~/lab$ head -n 14 hello.s
        .file   "hello.c"
        .text
        .section        .rodata
.LC0:
        .string "hello, world"
        .text
        .globl  main
        .type   main, @function
main:
.LFB0:
        .cfi_startproc
        endbr64
        pushq   %rbp
        .cfi_def_cfa_offset 16
learner@embeddex:~/lab$ # -c stops after assembling to an object file
learner@embeddex:~/lab$ gcc -c hello.c -o hello.o
learner@embeddex:~/lab$ # an ELF object file, not yet linked or runnable
learner@embeddex:~/lab$ file hello.o
hello.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
03

Object files, symbols, and the exit status

4 min read

An is the linker's unit of work. On Linux the object format is ELF, the Executable and Linkable Format. Inside are your translated instructions and a table that records which names this file defines and which it needs from elsewhere. nm prints that table:

bash
gcc -c hello.c -o hello.o
nm hello.o

Typical output (yours will differ):

shell
                 U printf
0000000000000000 T main

T marks main as defined text (code) in this file; U marks printf as undefined, a name this file expects someone else to provide. The linker's whole job is to make every U match a definition, and to resolve every reference to a real address. objdump -d hello.o disassembles the machine code back into readable assembly, the reverse of the stage above.

Because main is the function _start calls, it is the of your program. Nothing of yours runs before it. What main returns matters: its value is handed to the runtime's exit(), and becomes the process's . Your shell stores that status in a special variable called $?:

bash
gcc -o hello hello.c
./hello
echo $?

The program prints hello, world, then echo $? prints 0. Change return 0; to return 7;, rebuild, and echo $? prints 7. The status is a value from 0 to 255, because only the low eight bits survive the trip through the kernel. If main runs off the end without a return, the C standard since C99 makes it return 0 implicitly, but you should write return 0; anyway so the intent is visible.

A non-zero exit status is how a program says "I failed", and every script, build system and CI pipeline in the program depends on it. A test that passes returns 0; one that fails returns 1. An init script checks the status to decide whether a service started. The convention is so universal that <stdlib.h> defines EXIT_SUCCESS and EXIT_FAILURE for exactly this purpose.

Going deeperInside the object file: sections and relocation

An ELF object file is divided into sections. .text holds the machine code, .data holds initialised global variables, .rodata holds read-only constants such as the "hello, world\n" string, and .bss holds global variables that start as zero and therefore need no space in the file. nm letters label the section a symbol lives in: T for text, D for data, B for bss, U for undefined. The object file also carries relocation entries, small notes telling the linker "this instruction refers to the symbol printf, whose final address is not known yet". That is why a .o file is smaller and more abstract than the final executable: the addresses are still placeholders. You will meet ELF again in the M2 module, where you will read its headers and sections by hand.

The exit status pathmainreturns 0or anynon-zeroexit status0recorded bythe kernelshellstores $?variableholds itecho $?prints itshows thevaluemainreturns 0or anynon-zeroexit status0recorded bythe kernelshellstores $?variableholds itecho $?prints itshows thevalue
How main's return value travels to the kernel and reappears as the shell's $? variable.
Symbols with nm, and main's return as the exit status
learner@embeddex:~/lab$ # assemble only, no link yet
learner@embeddex:~/lab$ gcc -c hello.c -o hello.o
learner@embeddex:~/lab$ # T means defined here, U means undefined (printf)
learner@embeddex:~/lab$ nm hello.o
0000000000000000 T main
                 U puts
learner@embeddex:~/lab$ # the linker resolves printf from the C library
learner@embeddex:~/lab$ gcc -o hello hello.c
learner@embeddex:~/lab$ # run it
learner@embeddex:~/lab$ ./hello
hello, world
learner@embeddex:~/lab$ # main returned 0
learner@embeddex:~/lab$ echo $?
0
learner@embeddex:~/lab$ # build a program whose main returns 7
learner@embeddex:~/lab$ gcc -o exit7 exit7.c
learner@embeddex:~/lab$ # it prints nothing
learner@embeddex:~/lab$ ./exit7
learner@embeddex:~/lab$ # 7 comes back as the exit status
learner@embeddex:~/lab$ echo $?
7
04

Warnings, errors, and reading the compiler

4 min read

By default gcc is quiet about a great deal. The flags -Wall and -Wextra turn on the warnings that catch real bugs, and every command in this program uses them. -Werror goes one step further and treats every warning as an error, so a build with any warning fails. The practical habit is -Wall -Wextra while you work, and -Werror in the CI pipeline that guards the main branch.

A diagnostic has a fixed shape: the file name, a line, a column, a severity word, and the message. Consider a typo where a variable was never declared:

c
#include <stdio.h>
int main(void) {
    printf("%d\n", x);
    return 0;
}
bash
gcc -Wall -Wextra -o bug bug.c

Typical output (yours will differ):

shell
bug.c: In function 'main':
bug.c:3:20: error: 'x' undeclared (first use in this function)

bug.c:3:20 means file bug.c, line 3, column 20. An error means the compiler could not produce a translation it trusts, so it stops and writes no executable; gcc also returns a non-zero status. Now a program that compiles but deserves a warning:

c
#include <stdio.h>
int main(void) {
    int unused = 5;
    printf("ok\n");
    return 0;
}
shell
bug.c:3:9: warning: unused variable 'unused' [-Wunused-variable]

A warning means the compiler produced an executable anyway, and gcc returns 0. The square-bracket tag [-Wunused-variable] is the name of the warning, which you can silence or escalate by name. The difference is why warnings are dangerous: a build "succeeds" while carrying a likely bug, and in a clean build log nobody notices. An unused variable is harmless, but warnings such as -Wmaybe-uninitialized and -Wimplicit-function-declaration often point at genuine memory and correctness bugs.

The professional rule is to fix warnings, not hide them. Read the line and column, understand the message, and correct the code. Suppressing a warning with a cast or a pragma hides a symptom while the bug stays. For signed/unsigned mistakes specifically, GCC has -Wsign-compare (on by default for C++, and worth enabling by hand in C) and the broader -Wconversion, which flags any implicit conversion that loses information. Add them when a bug smells like a type problem:

bash
gcc -Wall -Wextra -Wsign-compare -o bug bug.c
Fix the first diagnostic first

One error often cascades into a dozen as the compiler loses track of the program. Fix the first diagnostic, recompile, and repeat; the rest frequently disappear with it.

Errors versus warningsErrorWarningCompilationstopsyesnoProduces abinarynoyesMeaningillegal codesuspiciouscodeYour actionfix beforerunningfix beforeshipping
The difference between an error, which stops the build, and a warning, which still produces a binary.
An error stops the build; a warning still succeeds
    3 |     printf("%d\n", x);
      |                    ^
bug.c:3:20: note: each undeclared identifier is reported only once for each function it appears
in
learner@embeddex:~/lab$ # an error means gcc returns non-zero and writes no binary
learner@embeddex:~/lab$ echo $?
1
learner@embeddex:~/lab$ # this compiles, but warns about the unused variable
learner@embeddex:~/lab$ gcc -Wall -Wextra -o warn warn.c
warn.c: In function ‘main’:
warn.c:3:9: warning: unused variable ‘unused’ [-Wunused-variable]
    3 |     int unused = 5;
      |         ^~~~~~
learner@embeddex:~/lab$ # a warning still returns 0 and writes a binary
learner@embeddex:~/lab$ echo $?
0
learner@embeddex:~/lab$ # -Werror turns that warning into a hard failure
learner@embeddex:~/lab$ gcc -Wall -Wextra -Werror -o warn2 warn.c
warn.c: In function ‘main’:
warn.c:3:9: error: unused variable ‘unused’ [-Werror=unused-variable]
    3 |     int unused = 5;
      |         ^~~~~~
cc1: all warnings being treated as errors
05

Types, sizeof, and the limits headers

4 min read

C's basic types split into integers and floating point. The integer types, in order of guaranteed minimum range, are char, short, int, long and long long; the floating-point types are float, double and long double. Each integer type has a signed form, able to hold negative and positive values, and an unsigned form, able to hold only zero and positives but roughly twice the maximum. The keywords are signed and unsigned, so unsigned int is a common type and unsigned alone means unsigned int.

The crucial fact for an embedded engineer is that the standard sets minimum ranges, not exact sizes. It guarantees char is one byte and sets minimum ranges that work out to short and int at least 16 bits, long at least 32 and long long at least 64, but your compiler is free to make them larger. For floating point it sets minimum precision rather than a size: on desktop Linux float and double are the IEEE 754 4- and 8-byte formats, but some small-microcontroller compilers (avr-gcc traditionally) make double only 4 bytes, the same as float. The operator tells you the truth on your machine:

c
#include <stdio.h>
#include <limits.h>
#include <float.h>

int main(void)
{
    printf("char      %zu\n", sizeof(char));
    printf("short     %zu\n", sizeof(short));
    printf("int       %zu\n", sizeof(int));
    printf("long      %zu\n", sizeof(long));
    printf("long long %zu\n", sizeof(long long));
    printf("float %zu  double %zu\n", sizeof(float), sizeof(double));
    printf("INT_MAX %d  INT_MIN %d  UINT_MAX %u\n", INT_MAX, INT_MIN, UINT_MAX);
    printf("FLT_DIG %d  DBL_DIG %d\n", FLT_DIG, DBL_DIG);
    return 0;
}

On x86-64 Linux this prints, typically (yours will differ):

shell
char      1
short     2
int       4
long      8
long long 8
float 4  double 8
INT_MAX 2147483647  INT_MIN -2147483648  UINT_MAX 4294967295
FLT_DIG 6  DBL_DIG 15

Notice two sizes are platform-defined. On x86-64 and 64-bit ARM, long is 8 bytes and pointers are 8 bytes; this is the LP64 data model. On 32-bit ARM and 32-bit x86, long is 4 bytes and pointers are 4 bytes; this is ILP32. A struct containing a long therefore changes size between the two, which silently changes binary layouts, memory maps and file formats when you move code from a laptop to a board. Never hardcode 4 or 8; ask sizeof.

The macros in <limits.h> give the exact ranges so you can avoid hardcoding those too: INT_MAX, INT_MIN and UINT_MAX for int, plus CHAR_MIN/CHAR_MAX, SHRT_MIN/SHRT_MAX, LONG_MIN/LONG_MAX, LLONG_MIN/LLONG_MAX and the unsigned maxima such as UCHAR_MAX and ULONG_MAX. Signed integers on essentially every system use two's complement, so a type with n bits spans -2^(n-1) through 2^(n-1) - 1 signed, and 0 through 2^n - 1 unsigned. <float.h> describes floating point: FLT_DIG (6) is the number of decimal digits you can round-trip through a float, DBL_DIG (15) through a double, and FLT_MAX, FLT_MIN and FLT_EPSILON give range and precision.

To print each type you must use the matching specifier: %d for signed int, %u for unsigned int, %x for hexadecimal, %f for a floating-point value, and %zu for the size_t that sizeof returns. Mismatching a specifier and an argument is a real bug, and the compiler will warn about it. The full specifier table comes later; for now the pairing is the thing to learn.

Going deeperWhy int is 4 bytes everywhere, and fixed-width types

The data models have names: LP64 (long and pointer are 64-bit) and ILP32 (int, long and pointer are 32-bit). int stays 32-bit in both because it is meant to be the natural word size that is fast to load and store, while long grew on 64-bit Unix to hold a pointer. This is Unix-specific: on 64-bit Windows, long is still 4 bytes. When a type must have an exact width regardless of target, use the fixed-width types from <stdint.h> such as int32_t and uint32_t. Those are the subject of the bit-manipulation session later in this module, but the idea to carry away now is that a bare int is a promise about a minimum range, not about a byte count.

Type sizes in two data modelsx86-64 LP6432-bit ARMILP32char1 byte1 byteshort2 bytes2 bytesint4 bytes4 byteslong8 bytes4 byteslong long8 bytes8 bytespointer8 bytes4 bytes
How the basic type sizes differ between the LP64 and ILP32 data models, in bytes.
sizeof reveals the platform's real type sizes
learner@embeddex:~/lab$ # compile with warnings on
learner@embeddex:~/lab$ gcc -Wall -Wextra -o sizes sizes.c
learner@embeddex:~/lab$ # on x86-64: long and pointers are 8 bytes (LP64)
learner@embeddex:~/lab$ ./sizes
int 4  long 8  pointer 8
INT_MAX 2147483647  UINT_MAX 4294967295
learner@embeddex:~/lab$ # the machine triple says x86_64, confirming LP64
learner@embeddex:~/lab$ uname -m
x86_64
06

Variables, scope, literals, and escape sequences

4 min read

A declaration introduces a name and its type; a definition also reserves the storage for it. At block scope the two coincide: int x; both declares and defines x, so it reserves space. A separate rule covers what you do not want to forget: initialise before use. int x = 0; declares, defines and initialises in one line. An automatic variable, one declared inside a function without the static keyword, has an indeterminate value until you initialise it, and reading it is a classic source of bugs that behave differently every run. Initialise every variable.

A variable's determines where it can be used. A variable declared inside a block lives from its declaration to the closing brace of that block, and is destroyed when the block exits. This is why the same name can be reused in different blocks, and why a variable declared inside a loop is fresh on every iteration. A name declared in an inner block shadows an outer one of the same name, which is legal but best avoided because it hides bugs.

Comments document intent and come in two forms: /* ... */ spans lines, while // runs to the end of the line. Neither can nest, and a stray */ or an accidental // can swallow code, so a compiler that reports a sudden flood of errors right after a comment is worth a second look.

Integer literals can be written in three bases. 42 is decimal, 0x2A is hexadecimal, and 052 is octal, all the same value. The leading zero is the trap: 010 is decimal 8, not 10, and padding numbers with zeros to align them silently changes their base. Suffixes pin the type: U for unsigned, L for long, LL for long long, combinable as UL or ULL. Without a suffix, a decimal literal takes the first of int, long, long long that fits, while a hexadecimal or octal literal also tries the unsigned variants. A floating-point literal without a suffix is a double, not a float; f forces float, L forces long double, and 1.5e3 is scientific notation for 1500.

42 decimal is 0x2A in hexadecimal and 052 in octal, all the same value; three ways to write one number.

  • value: 42
  • width: 8

Character constants are single characters in single quotes, and in C they have type int with the value of the character in the execution character set, so 'A' is 65 in ASCII. Characters that are awkward to type or print are written as escape sequences, a backslash followed by a code:

c
char nl  = '\n';   /* newline, byte 0x0A */
char tab = '\t';   /* tab, byte 0x09   */
char nul = '\0';   /* the zero byte     */
char bs  = '\\';   /* one backslash     */
char dq  = '\"';   /* a double quote    */
char hex = '\x41'; /* byte 0x41, 'A'    */

\0 is the null terminator that ends every C string, and you will meet it constantly. A hexadecimal escape keeps consuming hexadecimal digits, so '\x41A' asks for the value 0x41A, which does not fit in a char (gcc warns hex escape sequence out of range), a subtle trap when a hex escape is followed by a letter A-F or a digit; an octal escape stops after at most three digits. For an embedded engineer the practical payoff of hexadecimal literals is that register addresses, bit masks and device-tree values are all written this way, so reading 0x3F201000 as a UART base address should become second nature.

Common escape sequences\nnewline 0x0A\ttab 0x09\0zero byte\\one backslash\"double quote\x41byte 0x41a backslash escapes the nextcharacter
The common escape sequences and the byte each one stands for.
07

Operators and the precedence table

4 min read

The arithmetic operators are +, -, *, / and %. Integer division truncates toward zero, so 7 / 2 is 3 and -7 / 2 is -3, and % gives the remainder, 7 % 2 is 1, for integers only. Assignment is =, with shorthand forms +=, -=, *=, /=, %= that combine an operation and an assignment, so i += 3 means i = i + 3. Comparison uses ==, !=, <, >, <=, >=; the classic bug is writing = where == belongs, which assigns instead of compares and is legal C, so it compiles and behaves wrong.

The logical operators are && (and), || (or) and ! (not), and they short-circuit. && evaluates its left side first and, if that is false, skips the right side entirely because the whole expression is already false. || does the mirror: if the left is true, the right is not evaluated. This is not just an optimisation, it is a control-flow feature:

Step by stepHow short-circuit evaluation decides what runs
  1. Evaluate left: C computes the left operand of && or || first.

  2. Decide: for &&, a false left means the whole expression is false; for ||, a true left means the whole expression is true.

  3. Skip or run: only if the result is still undecided does C evaluate the right operand.

  4. Take the value: the expression yields 1 for true, 0 for false.

The idiom if (p != NULL && *p == 'x') relies on this: if p is null, *p is never dereferenced, so the check is safe. The increment and decrement operators ++ and -- come in two forms whose difference is a whole class of interview questions. Prefix ++i increments first, then the expression uses the new value. Postfix i++ uses the current value first, then increments:

c
int i = 10;
int j = 5 + i++;   /* j is 15, then i becomes 11 */
int k = 5 + ++i;   /* i becomes 12, then k is 17 */

The ternary ? : is an expression that picks one of two values, as in x > 10 ? 17 : 37. The comma operator sequences two expressions and yields the rightmost. The bitwise operators &, |, ^, ~, << and >> belong in the table but are the subject of the bit-manipulation session, so only their precedence matters here.

When several operators appear in one expression, precedence and associativity decide the grouping. The full table, highest first, with associativity:

text
()  []  .  ->                         left to right
++  --  (postfix)                     left to right
++  --  (prefix)  +  -  !  ~  *  &  (type)  sizeof   right to left
*  /  %                               left to right
+  -                                  left to right
<<  >>                                left to right
<  <=  >  >=                          left to right
==  !=                                left to right
&                                     left to right
^                                     left to right
|                                     left to right
&&                                    left to right
||                                    left to right
?:                                    right to left
=  +=  -=  *=  /=  %=  <<=  >>=  &=  ^=  |=   right to left
,                                     left to right

Two habits keep precedence from biting you. Read the table until the top five rows are automatic, and when in doubt, add parentheses: (a || b) && c is unambiguous where a || b && c is not, and a reviewer will thank you.

Operator precedencepostfix() [] . ->prefix unary! - ++ --multiply* / %add+ -compare< <= > >=equal== !=logical AND&&logical OR||assignment = is lowest;unary and assignment bindright-to-left
Operator precedence from highest to lowest, with associativity shown for the rows that differ.
08

Control flow: if, switch, and loops

1 min read

if runs a block when a condition is true, else runs a block when it is false, and chains of else if test a sequence of conditions in order. The condition is any expression, with zero meaning false and any non-zero value meaning true:

c
if (x > 0) {
    printf("positive\n");
} else if (x < 0) {
    printf("negative\n");
} else {
    printf("zero\n");
}

switch selects among integer constants, and compilers often turn it into a jump table, useful when many branches test the same variable against constants. Each case labels a value, default catches the rest, and break exits the switch. Omitting break causes fallthrough, where execution drops into the next case. Fallthrough is sometimes deliberate, which you mark with a comment or, in C23, the [[fallthrough]] attribute, but far more often it is the bug you forgot to add break:

c
switch (cmd) {
case 'a':
    printf("arm\n");
    break;
case 'd':
    printf("disarm\n");
    break;
default:
    printf("unknown\n");
    break;
}

switch works only on integer types, which includes char and enum, but not floating-point values or strings, so if/else still owns those comparisons. The three loops differ in where the test sits. while tests first and may run zero times. do/while tests last and always runs at least once, which suits a "prompt then read" loop. for packs initialisation, condition and update into one place:

c
int i = 0;
while (i < 3) { printf("%d ", i); i++; }   /* 0 1 2 */

i = 0;
do { printf("%d ", i); i++; } while (i < 3); /* 0 1 2 */

for (int j = 0; j < 3; j++) { printf("%d ", j); } /* 0 1 2 */

All three are interchangeable, and choosing is about readability: for when you know the count, while when you do not, do/while when the body must run at least once. break exits the nearest enclosing loop or switch immediately; continue skips the rest of the current iteration and jumps to the next test. In nested loops, break and continue only affect the innermost loop, so a break inside an inner loop does not stop the outer one, a frequent source of confusion.

Embedded firmware is full of switch statements: a state machine, a command parser and a device-mode dispatcher are all switches over an integer. The fallthrough trap and the nested-loop break trap are the two control-flow bugs you will actually ship if you are not paying attention.

while versus do-whilewhiledo-whileTests conditionbefore bodyafter bodyRuns zero timesyesnoRuns at leastoncenoyes
The difference between while, which tests first, and do-while, which tests after the body.
09

Conversions, the signed/unsigned trap, and undefined behaviour

5 min read

C performs implicit conversions in most expressions. The means that char a = 10, b = 20; int i = a + b; computes in int, which is why it works. Then the usual arithmetic conversions make the two operands of a binary operation a common type:

1promote the small integer types

Every char and short operand is promoted to int (or to unsigned int if int cannot hold every value).

2convert to a floating type if one is present

If either operand is float or double, the other is converted to that type. So 3 + 1.2 computes in double and yields 4.2.

3otherwise widen to the largest integer type

If both are integers, the narrower is converted to the wider, by a ranking from int through long and long long.

4signed gives way to unsigned

If one operand is unsigned and its type is at least as wide as the other's, the signed value is converted to that unsigned type. (If instead the signed type is wider and can hold every value of the unsigned one, the unsigned operand is converted to the signed type: unsigned int + long computes in long on 64-bit Linux.)

Step 4 is the trap. The signed value is reinterpreted modulo 2^n, so a negative number becomes a large positive one. Compare -1 with 1U:

c
if (-1 < 1U)
    printf("true\n");
else
    printf("false\n");   /* this prints: -1 became UINT_MAX */

Because 1U is unsigned, -1 is converted to unsigned int, becoming 4294967295 on a 32-bit int, and 4294967295 < 1 is false. The same rule turns a very common loop into an infinite one:

c
for (unsigned int i = n; i >= 0; i--)   /* never terminates */
    ;

When i reaches 0 and is decremented, it wraps to UINT_MAX, and UINT_MAX >= 0 is always true, so the loop spins forever. This is a real failure mode in device firmware, where a loop that never ends hangs the whole board.

signed=true shows -1 with bit pattern 0xFFFFFFFF; toggle signed off and the same 32 bits read 4294967295 (UINT_MAX). That is why -1 < 1U is false.

  • value: -1
  • width: 32

Common mistakes: symptom, cause, diagnose, fix. The symptom is a comparison that is always true or false, or a loop that never ends. The cause is an unsigned operand converting a signed operand to unsigned. Diagnose it by compiling with -Wsign-compare or -Wconversion, which point straight at the mixed comparison. Fix it by keeping signedness consistent: use matching types, or make the conversion explicit with a cast only after you have confirmed the values cannot go negative.

Casts write a conversion explicitly as (type) expression. Converting float to int truncates toward zero and is undefined behaviour if the value does not fit. Converting a large int to float loses precision silently. A cast is not a way to shut the compiler up; it is a statement you are taking responsibility for the conversion.

The last piece is the one that colours the whole program: . The classic first contacts are side effects without a sequence point (a moment, such as the end of a statement or the boundary of && or ||, where every earlier side effect is complete). Modifying the same variable twice with no sequence point between the writes, as in i++ + ++i or i = i++, is undefined behaviour. The order in which function arguments are evaluated is unspecified, so printf("%d %d", a(), b()) does not tell you whether a() or b() runs first, and you must not write code that depends on it. Undefined behaviour is not "your code crashes"; it is "the compiler is allowed to do anything", which in practice means a program that works at -O0 and breaks at -O2, or corrupts memory on the board but not in QEMU. You will meet sanitizers and the full defensive toolkit in a later session; for now the rule is to avoid constructs whose meaning is not defined, and to treat a compiler that stays silent only because it is allowed to be silent as a warning sign.

The usual arithmetic conversionsintegerpromotionschar andshort tointanyfloatingtype?convert allto itsamesignedness?widen tothe widertypesigned plusunsignedsignedbecomesunsignedintegerpromotionschar andshort tointanyfloatingtype?convert allto itsamesignedness?widen tothe widertypesigned plusunsignedsignedbecomesunsigned
The steps that convert two mixed-type operands into a common type before an operation.
-1 < 1U is false: the signed/unsigned trap
learner@embeddex:~/lab$ # compiles clean, but the comparison mixes signed and unsigned
learner@embeddex:~/lab$ gcc -Wall -Wextra -o trap trap.c
trap.c: In function ‘main’:
trap.c:3:12: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsi
gned int’ [-Wsign-compare]
    3 |     if (-1 < 1U)
      |            ^
learner@embeddex:~/lab$ # -1 was converted to UINT_MAX, so it prints false
learner@embeddex:~/lab$ ./trap
false
learner@embeddex:~/lab$ # -Wsign-compare points straight at the mixed comparison
learner@embeddex:~/lab$ gcc -Wall -Wextra -Wsign-compare -o trap trap.c
trap.c: In function ‘main’:
trap.c:3:12: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsi
gned int’ [-Wsign-compare]
    3 |     if (-1 < 1U)
      |            ^
10

printf and scanf in depth, and the numbers and characters that bite

4 min read

A format specifier starts with % and names the expected type. The core set: %d for signed int, %u for unsigned int, %x or %X for hexadecimal, %o for octal, %f for floating point, %e for scientific notation, %s for a string, %c for one character, %p for a pointer, and %zu for the size_t type. Because a float argument is promoted to double in a variadic call, %f prints both float and double. Width and precision refine the output: %6d pads an integer to six columns, and %.2f prints two decimal places. printf returns the number of characters it wrote, or a negative value on error, and checking that return is how a program notices a failed write.

One subtlety of buffering: stdout is line-buffered when it goes to a terminal but fully buffered when redirected to a file or a pipe. A program that prints a progress message and then crashes may lose that message, because it is still sitting in a buffer. fflush(stdout) forces pending output out immediately, which is exactly why you call it before a section of code that might crash, or in a loop that prints and then does risky work.

scanf is the input half of the pair, and it is the more dangerous one. It reads formatted input from stdin, needs a pointer for every argument (the address-of operator & in front of each variable), and returns the number of items it successfully read, which you must check:

c
int age;
printf("age: ");
fflush(stdout);
if (scanf("%d", &age) != 1) {
    printf("bad input\n");
    return 1;
}
printf("you are %d\n", age);

scanf uses %d, %f, %lf (for double, unlike printf), %s and %c, and %s reads a single whitespace-delimited word into a character array. The trap with %s is that it has no idea how big that array is, and longer input overflows it, which is the buffer overflow you will prevent once arrays and pointers arrive next lesson. The rule for now is to never call scanf("%s", ...) without a width limit.

scanf %s reads an unbounded word

scanf with %s writes input into your array with no idea how big the array is, and longer input overflows it. Until arrays and the width limit arrive next lesson, never call scanf with %s on untrusted input.

The documentation for all of this is one command away: man 3 printf and man 3 scanf list every specifier, flag and return value, and they are worth keeping open while you work.

Floating point has two properties that bite systems programmers. First, float holds about 7 decimal digits and double about 15, so a double is the default choice and a float is a deliberate space-saving trade. Second, most decimal fractions have no exact binary representation: 0.1 is a repeating fraction in binary, exactly as 1/3 is in decimal, so it is stored as the nearest representable value and arithmetic accumulates a small error. The consequence is the rule you will follow forever: never compare floating-point values with ==. Compare against a tolerance instead:

c
#include <math.h>
double a = 0.1 + 0.2;
if (fabs(a - 0.3) < 1e-9)
    printf("close enough\n");

fabs, sqrt, pow and the rest live in math.h, and on Linux the math library is separate, so link with -lm:

bash
gcc -o calc calc.c -lm

Finally, characters. ASCII defines bytes 0 to 127, and the locale defines what the upper half means, which is why a byte above 127 is not a portable letter. The signedness of plain char is implementation-defined: x86 gcc makes it signed, while most ARM toolchains, including aarch64-linux-gnu-gcc and arm-none-eabi-gcc, make it unsigned. So char c = 0xFF; yields -1 on x86 and 255 on ARM. This matters in two places: comparisons like c < 0 give opposite answers on the two targets, and the ctype.h functions such as tolower and isalpha require either an unsigned char value or EOF, so passing a possibly-negative char is undefined behaviour. The portable form is tolower((unsigned char) c). This is one small example of the program's standing theme: code that runs fine on the laptop and breaks on the board is usually a hidden type assumption, and this lesson has now handed you the tools to find it.

The 8 bits 0xFF read as 255 when unsigned but -1 when signed, which is why char c = 0xFF is -1 on x86 gcc and 255 on ARM toolchains.

  • value: 0xFF
  • width: 8
Going deeperHow a float is laid out in 32 bits

An IEEE 754 single-precision float packs 32 bits as one sign bit, an 8-bit biased exponent, and a 23-bit fraction, with the leading bit of the significand implicit. A double uses 1 sign bit, 11 exponent bits and 52 fraction bits, which is where the extra 8 digits of precision come from. FLT_EPSILON is the gap between 1.0 and the next representable float, so an absolute tolerance of FLT_EPSILON is only right near 1.0; for values far from 1.0 the gaps are larger, and a relative comparison such as fabs(a - b) <= DBL_EPSILON * fabs(a) scales correctly. The point for this lesson is not the layout itself but the consequence: a float is a finite set of points, and a decimal that falls in a gap is rounded to the nearest point, which is the origin of every "floating point is broken" complaint.

printf and scanf format specifiers%dsigned int%uunsigned int%xhexadecimal%ffloat or double%sstring%cone char%ppointer%zusize_t
The main printf and scanf format specifiers and the argument type each one expects.
11

Try it

1 min read

Open the lab for this session and build your first programs end to end. Write hello.c, then stop the compiler at each stage with -E, -S and -c, and read the generated .i, .s and .o files with a text editor, nm and objdump. Then write a small calculator that exercises every type, operator and control-flow construct, printing each result with the correct specifier. Finally, deliberately introduce a signed/unsigned comparison bug, a missing break in a switch, and a float == comparison, and read each diagnostic or wrong result until you can explain it. The practice pack has the exact commands and the list of bugs to reproduce.

Key takeaways

  • C is a compiled language: source becomes machine code through preprocess, compile, assemble and link, all driven by gcc.
  • An object file holds machine code plus a symbol table; main is the entry point the C runtime calls, and its return value becomes the exit status.
  • Compile with -Wall -Wextra and treat warnings as bugs; -Werror turns that policy into a hard failure.
  • Type sizes are platform-defined: int is 4 bytes on both x86-64 and 32-bit ARM, but long and pointers differ.
  • Operators have fixed precedence and associativity; && and || short-circuit, and prefix and postfix ++ differ.
  • Mixing signed and unsigned integers converts the signed value to unsigned, so -1 < 1U is false.
  • Floating point cannot represent most decimals exactly, so never compare floats with ==.
  • char is signed on some targets and unsigned on others, which matters for comparisons and the ctype functions.

Reflect

  1. Explain to a colleague, in two sentences: trace the four translation stages a C program passes through and name the sub-programs gcc runs for each.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?

On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

Practise this lessonExercises, quiz, interview preparation and spaced review

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close