The importance of break in the switch... case statement in C language, switch... casebreak

Source: Internet
Author: User

The importance of break in the switch... case statement in C language, switch... casebreak

The switch... case statement is often used in C language. Next I will introduce a detailed problem that needs to be paid attention to when using this statement. For example:

Example 1:

Switch (fruit)

{

Case 1: printf ("apple"); break;

Case 2: printf ("banana"); break;

Case 3: printf ("orange"); break;

Case 4: printf ("pear"); break;

Case 5: printf ("grape"); break;

}

When the fruit value is 1, there is no doubt that at this time, the program outputs apple; similarly, when the fruit value is 2, the output banana; when the fruit value is 3, the output orange; when the value of fruit is 4, pear is output; when the value of fruit is 5, grape is output. here is another example. In this example, we remove the break after case 3.

Example 2:

Switch (fruit)

{

Case 1: printf ("apple"); break;

Case 2: printf ("banana"); break;

Case 3: printf ("orange ");

Case 4: printf ("pear"); break;

Case 5: printf ("grape"); break;

}

In Example 2, when the value of fruit is 3, the program outputs orangepear. When the break after case 4 is also removed, when the value of fruit is 3, in this case, the program outputs orangepeargrape. comparing Example 1 and example 2, you should understand that break is on the switch... the importance of case statements cannot be easily ignored in writing programs! In addition, sometimes the break after case is deliberately omitted to implement a function in writing a program. In this case, you do not have to give an example. I believe this will happen during the process of writing a program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.