The basic course of C language (iii) input and output functions and control flow statements (17)

Source: Internet
Author: User
Tags exit constant numeric value printf
1.3.3 Switch statement
When writing a program, often encountered by the different circumstances of the multiple-path problem, then can be nested IF-ELSE-IF statements to implement, but If-else-if statement use inconvenient, and error prone. In this case, the Turbo C2.0 provides a switch statement. The format of the switch statement is:
Switch (variable)
{
CASE constant 1:
Statement 1 or null;
Case constant 2:
Statement 2 or NULL;
.
.
.
case constant N;
statement n or NULL;
Default
Statement n+1 or empty;
}
When executing a switch switch statement, the variable is compared to the constant after the case, and if one is equal, the statement under the constant is executed, and if not equal to any of the constants, the statement following the default is executed.
Attention:
A variable in 1.switch can be a numeric value, or it can be a character.
2. You can omit some cases and default.
3. Each case or default statement can be a statement body, but it does not need to be enclosed with "{" and "}".
In the following example, the variable in the switch is an integral type.
Example 19:
Main ()
{
int test;
for (test=0; test<=10; test++)
{
Switch (test)/* variable is integer number of switches statement */
{
Case 1:
printf ("%d\n", test);
Break /* EXIT Switch statement * *
Case 2:
printf ("%d\n", test);
Break
Case 3:
printf ("%d\n", test);
Break
Default
Puts ("Error");
Break
}
}
}
In the following example, the variable in the switch is character type.
Example 20:
#include <stdio.h>
Main ()
{
char c;
while (c!=27)/* Loop until the ESC key is closed * *
{
C=getch (); /* From the keyboard does not echo receive a character * *
Switch (c)
{
Case ' a ':/* receive the character ' a ' * *
Putchar (c);
Break /* EXIT Switch statement * *
Case ' B ':
Putchar (c);
Break
Default:/* received word Fu Fei ' A ' and ' B ' *
Puts ("Error");
Break
}
}
}

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.