Lesson content
Read, practise, then check your understanding
A C source file is a translation unit after preprocessing. It normally contains header inclusions, declarations, type definitions, and function definitions. C is case-sensitive: count, Count, and COUNT are different identifiers.
Anatomy of a program
#include <stdio.h>
static int square(int value); // declaration
int main(void) { // function definition
int number = 7; // declaration + initialization
printf("%d squared is %d\n", number, square(number));
return 0;
}
static int square(int value) {
return value * value;
}
The preprocessor line begins with #. Function and variable declarations tell the compiler a name and type. A definition supplies storage or a function body. Most statements end in ;; a compound statement groups statements inside {}.
Tokens and identifiers
The compiler reads tokens: keywords (int, return), identifiers, constants, string literals, operators, and punctuation. An identifier begins with a letter or underscore and continues with letters, digits, or underscores. Avoid names beginning with underscores at file scope or double underscores because many are reserved to the implementation.
Use names that express purpose:
double calculate_tax(double subtotal); // clear
double ct(double x); // unclear
Scope and blocks
A name declared in a block is visible from its declaration to the end of that block. Inner blocks may shadow outer names, but shadowing can make mistakes hard to see.
int total = 10;
if (total > 0) {
int discount = 2;
total -= discount;
}
// discount is no longer in scope
Keep a variable’s scope as narrow as practical. This reduces the number of places that can change it.
Comments and formatting
// comments run to the end of a line. /* ... */ comments can span lines but do not safely nest. Comments should explain intent, constraints, or surprising decisions—not repeat the syntax.
// Convert milliseconds to scheduler ticks, rounding upward.
ticks = (milliseconds + tick_ms - 1) / tick_ms;
Whitespace mostly separates tokens, so consistent indentation is for humans. Use an automatic formatter where possible.
main and exit status
Portable hosted signatures are int main(void) and int main(int argc, char *argv[]). argc counts command-line arguments; argv holds null-terminated strings, with the program name conventionally at argv[0].
Return EXIT_SUCCESS or EXIT_FAILURE from <stdlib.h> when the named meaning is clearer. Reaching the end of main is equivalent to returning zero in modern C, but an explicit return can improve teaching and consistency.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.