C Programming Tutorial 0/65 lessons ~6 min read Lesson 53

    Macros

    Macros are preprocessor text replacements — object-like (#define MAX 100) and function-like (#define SQR(x) ((x)*(x))).

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Macros are preprocessor text replacements — object-like (#define MAX 100) and function-like (#define SQR(x) ((x)*(x))).

    Understanding the topic

    Parentheses Wrap parameters and whole expression — avoid SQR(x+1) bugs.

    vs inline functions Macros have no type checking; functions are safer.

    • Parentheses — Wrap parameters and whole expression — avoid SQR(x+1) bugs.
    • vs inline functions — Macros have no type checking; functions are safer.

    Step-by-step explanation

    1. Parentheses — Wrap parameters and whole expression — avoid SQR(x+1) bugs.
    2. vs inline functions — Macros have no type checking; functions are safer.

    Informative example

    Example program:

    c
    #include <stdio.h>
    #define SQR(x) ((x) * (x))
    int main(void) {
    printf("%d\n", SQR(3 + 2));
    return 0;
    }

    Output

    25

    Execution workflow

    1Macros — step by step
    1 / 2

    Parentheses

    Wrap parameters and whole expression — avoid SQR(x+1) bugs.

    Best practices

    • Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
    • Give every variable a defined value before it is read.
    • Stay inside array bounds — C will not stop you from over-running a buffer.

    Common mistakes

    • Multiple evaluation of macro arguments
    • Missing parentheses in macro body

    Hands-on exercise

    Practice problems:

    • MAX macro for two values
    • DEBUG macro with #ifdef

    Summary

    Macros in C — Text substitution — constants and function-like macros.

    Ready to mark this lesson complete?Track your journey across the entire course.