The importance of break in switch...case statement in C language

Source: Internet
Author: User
Tags case statement pear

Switch...case statements are often used in the C language, let me show you a detailed question to be aware of when using this statement. Words not much to say, directly cite examples:

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 value of fruit is 1 o'clock, there is no doubt that the program outputs Apple at this time, and similarly, when the value of fruit is 2 o'clock, the output is banana, when the value of fruit is 3 o'clock, the output is orange, and when the value of fruit is 4 o'clock, the output is pear, and when the value of fruit is 5 o'clock, Output grape. Let me take another example, in which 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 o'clock, the program output is orangepear, when the break after case 4 is also removed, when the value of fruit is 3 o'clock, At this point the program output is orangepeargrape. In contrast to Example 1 and Example 2, you should understand the importance of break in the Switch...case statement, in the writing process must not easily ignore this problem! In addition, in the writing program sometimes in order to implement a function will deliberately omit the break after the case, there is no need for an example, I believe you will be in the process of writing procedures encountered this situation.

The importance of break in switch...case statement in C language

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.