Learn C function prototypes and the #define macro, with examples.
π What to learn on this page
β Must-know essentials
Define constants with #define PI 3.14159
Prototype: int add(int, int);
Macros are plain text substitution
β Read if you have time
Function-like macro pitfalls (SQUARE(3+1))
#ifdef / #endif conditional compile
const is type-safer
Function prototype — an "announcement" of a function
When you want to put a function definition below main, you need to announce it first with a prototype.
#include<stdio.h>intadd(int a, int b); // prototype (no body, semicolon required)intmain(void) {
printf("%d\n", add(3,5)); // can use it now
}
intadd(int a, int b) { // definition can come laterreturn a + b;
}
Why is a prototype needed?
The C compiler reads code top to bottom. When it encounters a call to an undeclared function, it reports an error (or warning).
Bad example: Defining a function after main without a prototype — the compiler may warn or fail to type-check arguments.
Three ways to fix it:
Put the function above main.
Put a prototype above main (the standard approach).
Put the prototype in a header file (.h) and #include it.
Macros (#define) — constants and shorthand
#define is a directive that performs text substitution before compilation. It's used for constants and short function-like definitions.
#define PI 3.14159// constant macro#define MAX_SIZE 100#define SQ(x) ((x)*(x)) // function-like macrointmain(void) {
double area = PI * 2.0 * 2.0;
int a[MAX_SIZE];
printf("5^2 = %d\n", SQ(5)); // -> ((5)*(5)) = 25
}
Caution: Macros are plain text substitution. SQ(x+1) becomes ((x+1)*(x+1)); without the parentheses, the arithmetic breaks. Always wrap each argument and the whole body in parentheses.
Try it yourself — prototype & macro
proto.c
Output
Click "Run" to execute...
π‘ Try these ideas too
Define #define PI 3.14159 and compute circle area
Make a parameterized macro #define SQUARE(x) ((x)*(x))
Conditional compile with #ifdef DEBUG
Remove the prototype and observe the compilation change