1. The Use of “do { … } while (0)” in C Macros

    Consider a countdown program.

    countdown.c:

    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char **argv)
    {
        int seconds = 3; 
    
        for (int i = seconds; i != 0; --i) {
            printf("%i... ", i);
            fflush(stdout);
            sleep(1);
        }
        puts("Go!");
    
        return 0;
    }
    

    The goal is to put the actual countdown code in a macro. It fits perfectly in a function, but a macro is used for illustration purposes.

    Read More