Visual C # 2005 Quick Start switch statement

Source: Internet
Author: User

Sometimes, when the IF statement is nested, all if statements look very similar because they are evaluated for an exact same expression, with the only difference being that each if statement compares the result of the expression with a different value. For example:

if (day == 0)
 dayName = "Sunday";
else if (day == 1)
 dayName = "Monday";
else if (day == 2)
 dayName = "Tuesday";
else if (day == 3)
 ...
else
 dayName = "Unknown";

In these cases, it is often necessary to rewrite the nested if statement into a switch statement, making the program more efficient and easier to understand.

Understanding the syntax of a switch statement

The syntax for the switch statement is as follows (Switch,case and default are keywords):

switch ( controllingExpression )
{
 case constantExpression :
  statements
  break;
 case constantExpression :
  statements
  break;
 ...
 default :
  statements
  break;
}

Controllingexpression (control expression) only one value at a time. Then, starting with the case whose constantexpression value is equal to the Controllingexpression value, all the statements underneath it will run until a break is encountered. The switch statement then ends, and the program continues execution from the first statement after the switch closes the curly brace and ignores the other case.

If any one of the constantexpression values is not equal to the value of controllingexpression, the statement under optional label default is run.

Note that if the value of the controllingexpression does not match any of the case labels, and no default tag is found, the program skips the entire switch statement and continues execution from the first statement after its closing brace.

For example, the preceding nested if statement can be rewritten as the following switch statement:

switch (day)
{
 case 0 :
  dayName = "Sunday";
  break;
 case 1 :
  dayName = "Monday";
  break;
 case 2 :
  dayName = "Tuesday";
  break;
 ...
 default :
  dayName = "Unknown";
  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.