Skip to main content

Switch versus user defined function

Short answer

switch is a built‑in statement for multi‑way branching based on a value, cannot be called, and does not promote code reuse. A user‑defined function is a separately written, callable block of code that can accept arguments and return a value, supporting modularity.

State with example, how switch( ) function differs from user defined function in computer programming language C.

switchUser-defined function
A selection statement of the language (keyword)A block of code written by the programmer, with a name
Chooses one of many blocks depending on a valuePerforms a specific task and can return a value
Cannot be called, and takes no argumentsIs called from other places and can take arguments
Written inside a function (such as main)Written separately and defined once
Does not support code reuseSupports code reuse and modularity
#include <stdio.h>
int square(int n)          /* user-defined function */
{
    return n * n;
}
int main(void)
{
    int choice = 2;
    switch (choice)        /* switch is a statement, not a function */
    {
        case 1: printf("One\n"); break;
        case 2: printf("Square of 6 = %d\n", square(6)); break;
    }
    return 0;
}

Output:

Square of 6 = 36

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →