Chapter 6 control statements

Source: Internet
Author: User

Chapter 6 control statements

There is a statement that you can find in each programming language control flow statement. In this chapter, I introduced the control statements of C #, which are divided into two main parts:
. Select statement
. Loop statement
If you are a C or C ++ programmer, a lot of information may make you feel similar. However, you must know that there are still some differences between them.

6.1 SELECT statement
When a SELECT statement is used, you define a control statement whose value controls which statement is executed. Two selection statements are used in C:
. If statement
. Switch statement

6.1.1 if statement
The first and most commonly used statement is the if statement. Whether the included statement is executed depends on the Boolean expression:
If (Boolean expression) Inclusion statement
Of course, there can also be else branches. When the value of a Boolean expression is false, the Branch will be executed:
If (Boolean expression) contains the else statement.
An example of checking a non-zero long string before executing some statements:

If (0! = StrTest. Length)
{
}

This is a Boolean expression. (! = Indicates not equal .) However, if you are from C or C ++, you may get used to writing code like this:
If (strTest. Length)
{
}

This does not work in C #, because the if statement only allows Boolean (bool) data type results, and the Length attribute object of the string returns an integer.
Integer ). The compiler will see the following error message:
Error CS0029: Cannot implicitly convert type int to bool (the int type Cannot be implicitly converted to bool .)

The above is the habit you must change, and the following will no longer encounter a value assignment error in the if statement:
If (nMyValue = 5 )...

The correct code should be

If (nMyValue = 5 )...

Because equal comparison is implemented by =, just like in C and C ++. Take a look at the following useful comparison operators (but not all data types are valid ):
==-- Returns true if the two values are the same.
! = -- Returns false if two values are different.
<, <=,>, >=-- Returns true if the link (less than, less than, or equal to, greater than, greater than, or equal to) is satisfied.
Each operator is executed through the overload operator, and such execution has a specification on the data type. If you compare two different types
There must be an implicit conversion to automatically create the necessary code. However, you can execute an explicit type conversion.
The code in listing 6.1 demonstrates different use cases of the if statement and how to use the string data type. This program
The main idea is to determine whether the first parameter passed to the application starts with an uppercase letter, lowercase letter, or number.

Listing 6.1 determining the character form

1: using System;
2:
3: class NestedIfApp
4 :{
5: public static int Main (string [] args)
6 :{
7: if (args. Length! = 1)
8 :{
9: Console. WriteLine ("Usage: one argument ");
10: return 1; // error level
11 :}
12:
13: char chLetter = args [0] [0];
14:
15: if (chLetter> =)
16: if (chLetter <= Z)
17 :{
18: Console. WriteLine ("{0} is uppercase", chLetter );
19: return 0;
20 :}
21:
22: chLetter = Char. FromString (args [0]);
23: if (chLetter> = a & chLetter <= z)
24: Console. WriteLine ("{0} is lowercase", chLetter );
25:
26: if (Char. IsDigit (chLetter = args [0] [0])
27: Console. WriteLine ("{0} is a digit", chLetter );
28:
29: return 0;
30 :}
31 :}

The first if language segment starting with row 7th checks whether the parameter array has only one string. If the conditions are not met, the program displays the usage information on the screen and
Stop running.
Multiple methods can be used to extract a single character from a string-you can use the character index as in row 13th, or you can use the static
FromString method, which returns the first character of the string.
16th ~ 20 rows of if statement blocks use a nested if statement block to check uppercase letters. The logical "and" Operator (&) can be used for lowercase letters
Check, and finally use the static function IsDigit of the Char class to check the number.
In addition to the "&" operator, there is another conditional logical operator, which represents the "& brvbar;" of "or ;". Two logical operations
All characters are short-circuited. For the "&" operator, it means that if the first result of the condition "and" expression returns a dummy value, the remaining condition "and"
The expression is no longer evaluated. Correspondingly, the "& brvbar;" operator is short-circuited when the first true condition is met.
What I want you to understand is that to reduce the computing time, you should put the expression most likely to make the value "Short Circuit" in front. You should also be clear about
Some values in the if statement may be replaced.

If (1 = 1 & brvbar; (5 = (strLength = str. Length )))
{
Console. WriteLine (strLength );
}

Of course, this is an exaggerated example, but it illustrates the point that the first statement is evaluated as true, and the second statement will not be executed.
Maintain the original value of the variable strLength. Give everyone a piece of advice: never assign a value to an if statement with conditional logical operators.

6.1.2 switch statement
Compared with the if statement, the switch statement has a control expression and contains statements that run according to the constants of the control expressions they are associated.

Switch (control expression)
{
Case constant expression:
Containing statements
Default:
Containing statements
}

The data types allowed by the control expression are sbyte, byte, short, ushort, uint, long, ulong, char, string, or enumeration class.
Type. As long as other data types can be implicitly converted to any of the above types, it is also good to use it as a control expression.
The switch statement is executed in the following sequence:
1. Evaluate the control expression
2. If the constant expression after the case label matches the value obtained by the control statement, the containing statement is executed.
3. If no constant expression meets the control statement, the statement contained in the default label is executed.
4. If there is no case tag and no default tag, the end of the switch CIDR block is switched.
Before proceeding to more details about the switch statement, see list 6.2, which shows how to use the switch statement to display the days of a month (ignore cross-year)
Listing 6.2 use the switch statement to display the number of days in a month

1: using System;
2:
3: class FallThrough
4 :{
5: public static void Main (string [] args)
6 :{
7: if (args. Length! = 1) return;
8:
9: int nMonth = Int32.Parse (args [0]);
10: if (nMonth <1 & brvbar; nMonth> 12) return;
11: int nDays = 0;
12:
13: switch (nMonth)
14 :{
15: case 2: nDays = 28; break;
16: case 4:
17: case 6:
18: case 9:
19: case 11: nDays = 30; break;
20: default: nDays = 31;
21 :}
22: Console. WriteLine ("{0} days in this month", nDays );
23 :}
24 :}


The switch CIDR block contains 13th ~ 21 rows. For C programmers, this looks very similar because it does not use break statements. Therefore, there is
Important differences in vitality. You must add a break statement (or a different jump statement) because the compiler will remind you that it is not allowed to go directly to the next part.
What is direct access? In C (and C ++), it is completely legal to ignore break and write the following code:
NVar = 1
Switch (nVar)
{
Case 1:
DoSomething ();
Case 2:
DoMore ();
}

In this example, after the code of the first case statement is executed, the code of other case labels is directly executed until a break statement exits.
Switch CIDR block. Although sometimes this is a powerful feature, it often produces hard-to-find defects.
But if you want to execute other

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.