With #define SQUARE(x) x*x, evaluate int a = SQUARE(2+3); and int b = 64 / SQUARE(4);. Then redo both with #define SQUARE(x) ((x)*(x)).
Before compilation, the C preprocessor pastes in #include files, expands #define macros and selects code with #if/#ifdef; the compiler, assembler and linker then build the executable. Macro pitfalls, # and ##, include guards and the build stages are frequently tested.
#include <file> searches the system directories; #include "file" searches the source file's own directory first, then the system ones.#define SQUARE(x) ((x) * (x)): bracket every parameter and the whole body, or SQUARE(a + 1) becomes a + 1 * a + 1.# turns a macro parameter into a string literal; ## pastes two tokens into one.Turning prog.c into a program you can run takes four stages. gcc prog.c -o prog runs them all, but you can stop after any stage and inspect its output — exam questions often ask which stage produces which file, or which stage reports which mistake.
| Stage | Tool | Input → output | gcc flag | What happens |
|---|---|---|---|---|
| 1. Preprocessing | preprocessor (cpp) | prog.c → prog.i | -E | expands #include and macros, handles #if, removes comments |
| 2. Compilation | compiler proper (cc1) | prog.i → prog.s | -S | checks syntax and types, optimises, emits assembly language |
| 3. Assembly | assembler (as) | prog.s → prog.o | -c | translates assembly into machine code: an object file with a symbol table |
| 4. Linking | linker (ld) | prog.o + libraries → prog (a.out, .exe) | none | joins object files, resolves external symbols such as printf, writes the executable |
$ gcc -E prog.c -o prog.i # stop after preprocessing (readable text)
$ gcc -S prog.i # compile to assembly: prog.s
$ gcc -c prog.s # assemble into an object file: prog.o
$ gcc prog.o -o prog # link into an executable
$ ./prog # the loader copies it into memory and runs it
$ gcc -save-temps prog.c # do everything, but keep prog.i, prog.s and prog.o| Mistake | Reported by |
|---|---|
#include <stdoi.h> (no such header) | preprocessor — 'file not found' |
| missing semicolon, undeclared variable, type mismatch | compiler — syntax or semantic error |
| calling a function that no file defines, or an extern variable never defined | linker — 'undefined reference' (calling an undeclared function also draws a compiler error or warning in C99 and later) |
| division by zero, NULL dereference, runaway recursion | nothing at build time — the program fails at run time |
Preprocessor directives are lines whose first non-blank character is #. They are carried out before compilation — the compiler never sees them, only their result. A directive ends at the end of its line (a backslash \ at the end continues it onto the next line) and takes no semicolon. The preprocessor works on tokens and text; it knows nothing about C types, scopes or values.
#include <stdio.h> searches the implementation's system include directories — used for standard and installed library headers.#include "student.h" searches the directory of the current source file first, then the system directories — used for your own headers.gcc -I dir adds directories to the search path..c file./* ---------- student.h ---------- */
#ifndef STUDENT_H /* include guard: true only the first time */
#define STUDENT_H
#define MAX_NAME 30
struct student {
int roll;
char name[MAX_NAME];
};
void print_student(const struct student *s);
#endif /* STUDENT_H */
/* ---------- main.c ---------- */
#include <stdio.h> /* system header: angle brackets */
#include "student.h" /* own header: quotes */
#include "student.h" /* harmless: the guard skips this copy */struct student twice — a compile error. #pragma once at the top of a header does the same job and is supported by GCC, Clang and MSVC, but it is not part of the C standard; the #ifndef guard is fully portable.#define NAME replacement creates a macro: from that line to the end of the file (or until #undef NAME), every occurrence of the identifier NAME is replaced by the replacement text — but not inside string literals, character constants or longer identifiers. An object-like macro has no parameters and usually names a constant; a function-like macro takes arguments.
#include <stdio.h>
#define PI 3.14159 /* object-like: no type, no storage, no ';' */
#define MAX_STUDENTS 60
#define AREA(r) (PI * (r) * (r)) /* function-like: '(' right after the name */
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define SWAP(t, x, y) do { t tmp_ = (x); (x) = (y); (y) = tmp_; } while (0)
int main(void)
{
int scores[MAX_STUDENTS]; /* a macro is a true constant expression */
int p = 3, q = 8;
scores[0] = MAX(p, q);
SWAP(int, p, q); /* multi-statement macro used like a call */
printf("%.2f %d %d %d\n", AREA(2.0), scores[0], p, q); /* 12.57 8 8 3 */
printf("PI is not replaced inside strings\n");
#undef PI /* from here on PI is undefined again */
return 0;
}(. #define F(x) x+1 has a parameter, but #define F (x) x+1 defines an object-like F whose replacement is (x) x+1.; becomes part of the replacement: #define N 10; turns int a[N]; into int a[10;];, a syntax error.#undef it first.#define LIMIT 100const int limit = 100;Macro expansion is blind text pasting, so operator precedence and side effects can produce surprising results. Two rules prevent most trouble: wrap every parameter in brackets, and wrap the whole body in brackets.
| Macro | Use | Expands to | Result |
|---|---|---|---|
#define SQUARE(x) x * x | SQUARE(3 + 1) | 3 + 1 * 3 + 1 | 7, not 16 |
#define SQUARE(x) x * x | 64 / SQUARE(4) | 64 / 4 * 4 | 64, not 4 |
#define SQ(x) (x) * (x) | 100 / SQ(5) | 100 / (5) * (5) | 100 — the body needs outer brackets too |
#define SQ(x) ((x) * (x)) | SQ(3 + 1), 100 / SQ(5) | ((3 + 1) * (3 + 1)), 100 / ((5) * (5)) | 16 and 4 — correct |
#define DOUBLE(x) x + x | 3 * DOUBLE(4) | 3 * 4 + 4 | 16, not 24 |
#define PRODUCT(a, b) a * b | PRODUCT(2 + 3, 4) | 2 + 3 * 4 | 14, not 20 |
Arguments are substituted, not evaluated, so an argument with a side effect runs as many times as its parameter appears in the body. With #define SQ(x) ((x) * (x)), SQ(i++) becomes ((i++) * (i++)) — undefined behaviour. With #define MAX(a, b) ((a) > (b) ? (a) : (b)), MAX(x++, y) increments x twice whenever x is the larger value; the ?: sequence point makes that well-defined, but rarely what was meant.
#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
static inline int max_fn(int a, int b) { return a > b ? a : b; }
int main(void)
{
int x = 5, y = 3;
int z = MAX(x++, y); /* ((x++) > (y) ? (x++) : (y)): x++ runs twice */
printf("%d %d\n", z, x); /* 6 7 */
x = 5;
z = max_fn(x++, y); /* a function evaluates its argument once */
printf("%d %d\n", z, x); /* 5 6 */
return 0;
}do { … } while (0), as SWAP is in the previous section. Then if (c) SWAP(int, a, b); else … still works; with bare braces, the ; after the macro call would end the if statement and leave the else orphaned.Inside a function-like macro, #param (stringising) turns the argument into a string literal, and a ## b (token pasting) glues two tokens into a single token. Combined with the concatenation of adjacent string literals ("ab" "cd" is "abcd"), they let macros generate both code and text.
#include <stdio.h>
#define STR(x) #x /* stringise the argument */
#define XSTR(x) STR(x) /* expand first, then stringise */
#define PRINT(v) printf(#v " = %d\n", v) /* print a name and its value */
#define CAT(a, b) a ## b /* paste two tokens */
#define VERSION 3
int main(void)
{
int count = 5, var1 = 42;
PRINT(count); /* count = 5 */
printf("%d\n", CAT(var, 1)); /* var1 -> 42 */
printf("%s %s\n", STR(VERSION), XSTR(VERSION)); /* VERSION 3 */
printf("%s\n", STR(a + b)); /* a + b */
return 0;
}Why the extra XSTR? An argument used with # or ## is not macro-expanded first, so STR(VERSION) gives "VERSION". Passing it through a second macro — XSTR(VERSION) → STR(3) → "3" — expands the argument before it is stringised. C99 also added variadic macros, such as #define LOG(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__).
Conditional directives include or skip blocks of source before compilation, so skipped code never reaches the compiler at all. #if tests an integer constant expression (macros and defined(NAME) are allowed); #ifdef NAME and #ifndef NAME test whether a macro is defined; #elif and #else give alternatives; and every block ends with #endif.
#include <stdio.h>
#define DEBUG 1
#define VERSION 2
int main(void)
{
#if VERSION >= 2 && defined(DEBUG)
printf("v2 debug build\n"); /* compiled: both tests are true */
#elif VERSION == 1
printf("v1 build\n");
#else
printf("other build\n");
#endif
#ifdef _WIN32
printf("Windows\n"); /* only when compiling for Windows */
#else
printf("not Windows\n");
#endif
#if 0
this text is never compiled, so it need not even be valid C
#endif
return 0;
}#ifdef DEBUG … #endif and switch it on from the command line with gcc -DDEBUG prog.c (-DNAME=value gives a value; -UNAME removes a definition)._WIN32 and __linux__.#ifndef FILE_H / #define FILE_H / … / #endif makes a header safe to include any number of times./* */ comments — with #if 0 … #endif.assert(cond) from <assert.h> is itself conditional: defining NDEBUG before including the header turns every assert into nothing.| Directive | Purpose |
|---|---|
#undef NAME | removes a macro definition |
#error message | stops compilation with the message — e.g. when a required macro is missing |
#warning message | prints a warning and continues (standard since C23; long a GCC/Clang extension) |
#pragma … | implementation-specific instructions such as #pragma once, #pragma pack(1) and OpenMP's #pragma omp parallel; unknown pragmas are ignored |
#line n "file" | sets the line number and file name the compiler reports (used by code generators) |
# on its own | the null directive, which does nothing |
| Macro | Expands to | Example |
|---|---|---|
__FILE__ | the current source file name (a string) | "prog.c" |
__LINE__ | the current line number (an int) | 42 |
__DATE__ | the compilation date (a string) | "Dec 3 2026" |
__TIME__ | the compilation time (a string) | "10:15:30" |
__STDC__ | 1 when the compiler conforms to the standard | 1 |
__STDC_VERSION__ | the C standard in use (a long) | 199901L (C99), 201112L (C11), 201710L (C17), 202311L (C23) |
__func__ (C99) | the current function's name — a predefined identifier, not a macro | "main" |
#include <stdio.h>
#define TRACE() printf("%s:%d in %s()\n", __FILE__, __LINE__, __func__)
int main(void)
{
TRACE(); /* e.g. prog.c:7 in main() */
printf("compiled on %s at %s\n", __DATE__, __TIME__);
#if __STDC_VERSION__ >= 201112L
printf("C11 or later\n");
#endif
return 0;
}Try the problem first, then reveal the working one step at a time.
With #define SQUARE(x) x*x, evaluate int a = SQUARE(2+3); and int b = 64 / SQUARE(4);. Then redo both with #define SQUARE(x) ((x)*(x)).
With #define MAX(a, b) ((a) > (b) ? (a) : (b)) and int x = 5, y = 3;, what are z and x after int z = MAX(x++, y);?
Given #define AND &&, #define OR ||, #define LE <=, #define GE >= and char ch = 'D';, what does if ((ch GE 65 AND ch LE 90) OR (ch GE 97 AND ch LE 122)) printf("alphabet"); else printf("not an alphabet"); print? What if OR had been defined as !! instead?
Classify each problem by the stage that reports it: (a) #include <stdoi.h>; (b) int x = 5 with no semicolon; (c) calling area(2.0) when a prototype is present but no file defines area; (d) printf("%d", 10 / n); with n = 0 at run time; (e) a header whose #ifndef has no matching #endif.
Expand and evaluate: (a) #define CUBE(x) (x*x*x) used as CUBE(1+1); (b) #define DBL(x) x+x used as 5 * DBL(3); (c) #define HALF(x) x/2 used as HALF(10+6).
With #define ABS(x) x < 0 ? -x : x, what is ABS(-5 - 1)? Explain, and write a correct macro.
Write an include guard for a header named list.h, and explain what goes wrong without it when two other headers both include list.h.
Predict the output, given #define STR(x) #x, #define XSTR(x) STR(x), #define VER 3, #define CAT(a, b) a##b and int ab = 7;: printf("%s %s %d", STR(VER), XSTR(VER), CAT(a, b));
Give the gcc command for each task, and the file it produces from prog.c: (a) preprocess only; (b) produce assembly; (c) produce an object file without linking; (d) build an executable named app with the macro DEBUG defined.
#define SQUARE(x) x*x breaks for SQUARE(a + 1) and 100 / SQUARE(5) — bracket each parameter and the whole body.( makes it object-like: #define F (x) x+1 defines F as (x) x+1.i++) may be evaluated twice inside a macro; an inline function evaluates them once.; at the end of a #define becomes part of every expansion (#define N 10; breaks int a[N];).#include "x.h" searches the current directory first, <x.h> only the system paths; #pragma once is common but not standard — include guards are portable.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.