Use Switch's attention

xiaoxiao2021-03-06  85

The control process of the Switch statement can pass and execute each Case section at a time. just like:

Switch (color) {casse 1: Printf ("reds"); Break; Case 2: Printf ("Yellows"); Break; Case 3: Printf ("blues"); Break; Default: Printf ("Whites"); Break;

At this time, it will print Reds, Yellows, Blues, Whites according to the value of the variable Color, 1, 2, 3, or other, respectively.

If you change the code: Switch (color) {case 1: Printf ("reds"); case 2: Printf ("Yellows"); Case 3: Printf ("blues"); default: printf ("whites");} If the color value is 2, the program will promise from YellowsBluesWhites, because the program's control process is in order to perform the second PrintF call, will naturally perform sequentially. So, use the switch statement with the following attention: 1. Every CASE statement is added to add BREAK. If you don't need to add, it is best to add a comment / * Fall through * / explain, and the break after Default is just an individual habit, you can not add. Switch (color) {casse 1: Printf ("reds"); Break; Case 2: / * Fall THROUGH * / CASE 3: Printf ("blues"); Break; default: Printf ("whites"); Break;} 2. Don't forget the last Default branch. Even if the program really does not need Default processing, the statement Default: Break should also be reserved. Do not do more, but to prevent others from mistaken to think that you forgot DEFAULT.

[Some Are Referred from << C Traps and Pitfalls >> and << High Quality C / C Programming Guide >>]

转载请注明原文地址:https://www.9cbs.com/read-105906.html

New Post(0)