Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

c - What if I don't write default in switch case?

int a = 10;
switch(a){
case 0:
    printf("case 0");
    break;
case 1:
    printf("case 1");
    break;
}

Is the above code valid?

If I am sure that int a will not have any other value than 1 and 0, can I avoid default?

What if in any case a value will be different from 1 and 0?

I know this is a silly question but I was thinking that perhaps it would be illegal or undefined behavior soI just asked to make sure.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The code is valid. If there is no default: label and none of the case labels match the "switched" value, then none of the controlled compound statement will be executed. Execution will continue from the end of the switch statement.

ISO/IEC 9899:1999, section 6.8.4.2:

[...] If no converted case constant expression matches and there is no default label, no part of the switch body is executed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...