Learn C function prototypes and the #define macro, with examples.
#define PI 3.14159int add(int, int);SQUARE(3+1))#ifdef / #endif conditional compileconst is type-safermain, you first need to announce it with a prototype.#include<stdio.h> int add(int a, int b); // prototype (no body, semicolon required) int main(void) { printf("%d\n", add(3,5)); // can use it now } int add(int a, int b) { // definition can come later return a + b; }
main without a prototype. The compiler may warn and can't type-check the arguments properly.main.main (the standard approach)..h) and #include it.#define is a directive that performs text substitution before compilation. It's handy for constants and short function-like shortcuts.#define PI 3.14159 // constant macro #define MAX_SIZE 100 #define SQ(x) ((x)*(x)) // function-like macro int main(void) { double area = PI * 2.0 * 2.0; int a[MAX_SIZE]; printf("5^2 = %d\n", SQ(5)); // -> ((5)*(5)) = 25 }
SQ(x+1) expands to ((x+1)*(x+1)) β but without the parentheses, the arithmetic breaks. Always wrap each argument and the whole body in parentheses.#define PI 3.14159 and compute the area of a circle#define SQUARE(x) ((x)*(x))#ifdef DEBUG for conditional compilationCheck your understanding of this lesson!
Prototypes let the compiler type-check calls that appear before the function's actual definition.
#define PI 3.14 define?#define is a preprocessor macro — it performs text substitution before compilation, so it doesn't use any memory at runtime.
#include "myfile.h" and #include <stdio.h>?"" searches the current directory first, while <> looks in the system's standard directories. Use "" for your own headers.