Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Alex Avatar asked Sep 16 '25 10:09

Alex


2 Answers

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.

like image 104
ouah Avatar answered Sep 18 '25 23:09

ouah


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;

like image 36
lakshmen Avatar answered Sep 18 '25 22:09

lakshmen