Alex
Alex

Reputation: 10126

What does switch do if there is no default case?

I have found a following piece of code:

switch(val){
    case 0:
        // some actions
       break;
    case 1:
        // some actions
       break;
    case 2:
        // some actions
       break;
}

But it is not clear enough what will happen in the case of e.g val = 10?

I tried to test this code in a short program with incorrect value, and nothing had happen - program exited normally.

Can this code cause any potential error? Is there any guarantee that nothing will happen?

Upvotes: 4

Views: 5037

Answers (3)

ouah
ouah

Reputation: 145829

It will simply do nothing and not enter in any case.

It is recommended to have a default clause as the final clause in a switch statement. Programs like Lint will warn if you forget the default clause. And for information note that the default clause is required in MISRA-C.

EDIT:

I personally prefer it to be the final clause but I think the most important is for the final clause to be present. Why I prefer it to be the final clause is because of the Principle of least astonishment: people are used to see it as the final clause so I think it eases the program reading.

And just for information as I mentioned Lint and MISRA-C in my answer: PC-Lint / flexelint will not warn if default is present but not as the final clause and MISRA-C explicitly requires default to be present as the final clause.

Upvotes: 6

nabroyan
nabroyan

Reputation: 3275

If you use any other value from 0, 1, 2 (in this example) nothing will happen. val will be compared with all values that are in cases and if it will not be equal to one of them, it just will jump to the next statement.

Upvotes: 1

lakshmen
lakshmen

Reputation: 29064

That is why you should have a default case. It will handle cases other than those you typed.

What Happens in your case is that, it checks the case 0 and it doesn't match and checks case 1 and it also doesn't match and checks the case 2 and it again doesn't match. so it exits..

So it should be this way:

switch(val){
    case 0:
        // some actions
       break;
    case 1:
        // some actions
       break;
    case 2:
        // some actions
       break;
    default:
       //some actions
       break;
}

Another small point to note: it should case 0: not case 0;

Upvotes: 1

Related Questions