You may not know the switch

Source: Internet
Author: User

One:

Int I = 0;

Switch (I)
{
Case 0:
Console. WriteLine ("0 ");
Case 1:
Console. WriteLine ("1 ");
Break;
}


// Here, you want to execute

// Console. WriteLine ("0"), and then "fall through" to the lower layer to execute Case 1.

// However, "fall through" is not allowed in C. Unless none of the "case 0" statements exist.

However, you can use the goto statement to implement "fall through"

 

Int I = 0;
Switch (I)
{
Case 0:
Console. WriteLine ("0 ");
Goto case 1;
Case 1:
Console. WriteLine ("1 ");
Break;
} In C #, every case xxx is a tag, so you can use the goto statement to redirect.

 

Two:
 

 

Here, the default statement does not do anything, but does not add break;

The prompt is as follows:

 

C # Strictly control that the branches of each Switch are not allowed to run through ("fall through"). For example, sometimes you may look like the following:

 

This statement is completely legal.

 

Three:
Sometimes you define variables in case, but the variables may have the same name, for example:

 

Two identical variables, y, are defined in case 0 and case 1. The Compiler prompts the following error:

 

To solve this problem, add "{}" to convert the Case statement into a BLOCK statement.

 

Of course, there is also an unknown solution, as shown below:

 

 

 

Four:
Suppose you have a method M and the code is as follows:

Int M (bool B)
{
Switch (B)
{
Case true: return 1;
Case false: return 0;
}
} It is obvious that B has only two values, one being true and the other being false, but the compiler fails. The prompt is:

 

The compiler considers that every switch structure can be executed and does not execute it. However, method M must have an int return value, so the compiler prompts an error.

The solution to this problem is also simple:

Int M (bool B)
{
Switch (B)
{
Case true: return 1;
Default: return 0;
}
} Or:

Int M (bool B)
{
Return B? 1: 0;
}

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.