Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...