Example of C switch

This is an example program demonstrating the use of switch in C.

#include <stdio.h>

int main (int argc, char ** argv)
{
    switch (argc) {

    case 0:
        printf ("There are no arguments. Is everything OK?\n");
        break;

    case 1:
        printf ("There is one argument, %s (the name of the program).\n",
                argv[0]);
        break;
    case 2:
        printf ("There are two arguments, %s and %s.\n",
                argv[0], argv[1]);
        break;
    default:
        printf ("There are %d arguments.\n", argc);
        break;
    }
    return 0;
}

(download)

When run like

./se 

the output of the example looks like this:

There is one argument, ./se (the name of the program).

When run like

./se  a

the output of the example looks like this:

There are two arguments, ./se and a.

When run like

./se a b

the output of the example looks like this:

There are 3 arguments.


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer