Question:

How does the switch function works in C programming language?

by Guest59490  |  earlier

0 LIKES UnLike

Suppose I write a switch function in 2 ways:

1) Default is written as the last case

2) Default is written in the middle of switch function. i.e. there are some cases after default.

In the both cases, the function performs in the same manner.

Why is it so? Please explain its working.

 Tags:

   Report

2 ANSWERS


  1. you see switch works by testing case by case

    ex:

    switch(x)

    case 1

    case 2

    case 3

    default

    the variable being tested is x, if x = 1,2 or 3 their corresponding cases will be selected but if x doesnt match anything then DEFAULT  is selected thus default can be put anywhere either it be middle or end

    reffering to the guy below me.

    ofcourse there should be BREAKS, cause if there arent any then if the parameter switch(x) falls into case 1, but case 1 doesnt have a BREAK then the action of the next case with a break or up until it reaches the deafualt would be initializeed


  2. Normally, they won't perform in the same manner. For example, try these two functions:

    int Func1(int j)

    {

    int r=0;

    switch(j)

    {

      case 1: r++;

      default: r++;

    }

    return r;

    }

    int Func2(int j)

    {

    int r=0;

    switch(j)

    {

      default: r++;

      case 1: r++;

    }

    return r;

    }

    You will see that Func1(1) returns 2 while Func2(1) returns 1.

    If they performed the same it is because of something about the way you constructed your function. For example, perhaps you put a 'break' after every case but the last. In that case, the order of the cases doesn't matter. (Why would it?)

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.