Search code examples
cgeneric-programming

How to print a 1 to N without using semicolon ? Explain this code


// A recursive C program to print all numbers from 1
// to N without semicoolon 
#include<stdio.h>
#define N 10

int main(int num)
{
    if (num <= N && printf("%d ", num) && main(num + 1))
    {
    }     
}

How is this program working ?. Please Explain this


Solution

  • The code in this awful example relies on some fragile assumptions:

    main is called with 2 arguments: an int representing the number of arguments, including the program name, and an array of char* containing the argument string terminated by a NULL.

    The example assumes that defining main() with a single int argument will produce code compatible with this calling convention, which may or may not be valid and is explicitly described as having undefined behavior by the C Standard (J.2).

    If it is valid or works by chance, the int argument received by main will be 1 if the program is called from the command line without arguments.

    main() tests if this argument is <= N, is other words if the value is to be printed. If so, it invokes printf("%d ", num), which outputs the decimal representation of num to stdout and returns the number of characters produced, 2 for the first number, which is non zero, so the code goes on and invokes main recursively, passing it the next higher number.

    The goes on until all numbers up to N have been printed and the first test in the last recursive call fails.

    main then returns 0 (if the compiler is complies with the C99 or a later standard). Each recursive call returns 0 until the initial call returns 0 to the system.

    The code is fragile because main is invoked in a non standard way. It would be slightly less ugly to write:

    #include <stdio.h>
    
    #define N 10
    
    int main(int argc, char *argv[]) {
        if (num <= N && printf("%d ", num) && main(num + 1, argv)) {}
    }
    

    Note however that calling main() recursively is generally considered bad practice.