📄 ct2
字号:
.NHIf; relational operators; compound statements.PPThe basic conditional-testing statement in Cis the.UL ifstatement:.E1c = getchar( );if( c \*= '?' ) printf("why did you type a question mark?\\n");.E2The simplest form of.UL ifis.E1if (expression) statement.E2.PPThe condition to be tested is any expression enclosed in parentheses.It is followed by a statement.The expression is evaluated, and if its value is non-zero,the statement is executed.There's anoptional.UL elseclause, to be described soon..PPThe character sequence `==' is one of the relational operators in C;here is the complete set:.E1\*= equal to (\*.EQ\*. to Fortraners)!= not equal to> greater than< less than>= greater than or equal to<= less than or equal to.E2.PPThe value of.UL ``expression.UL relation.UL expression''is 1 if the relation is true,and 0 if false.Don't forget that the equality test is `==';a single `=' causes an assignment, not a test,and invariably leads to disaster..PPTests can be combined with the operators .UL `&&'.UC (AND),.UL `\*|'.UC (OR),and.UL `!'.UC (NOT).For example, we can test whether a character is blank or tab or newlinewith.E1if( c\*=' ' \*| c\*='\\t' \*| c\*='\\n' ) \*.\*.\*..E2C guarantees that.UL `&&'and.UL `\*|'are evaluated left to right _we shall soon see cases where this matters..PPOne of the nice things about C is that the.UL statementpart of an .UL ifcan be made arbitrarily complicatedby enclosing a set of statementsin {}.As a simple example,suppose we want to ensure that.UL ais bigger than.UL b,as part of a sort routine.The interchange of.UL aand.UL btakes three statements in C,grouped together by {}:.E1.ne 5if (a < b) { t = a; a = b; b = t;}.E2.PPAs a general rule in C, anywhere you can use a simple statement,you can use any compound statement, which is just a number of simpleor compound ones enclosed in {}.There is no semicolon after the } of a compound statement,but there.ulisa semicolon after the last non-compound statement inside the {}..PPThe ability to replace single statements by complex ones at willis one feature that makes C much more pleasant to use than Fortran.Logic (like the exchange in the previous example) which would require several GOTO's and labels in Fortran canand shouldbedone in C without any, using compound statements..NHWhile Statement; Assignment within an Expression; Null Statement.PPThe basic looping mechanism in C is the.UL whilestatement.Here's a program that copies its input to its outputa character at a time.Remember that `\\0' marks the end of file..E1main(~) { char c; while( (c=getchar(~)) != '\\0' ) putchar(c);}.E2The.UL whilestatement is a loop, whose general formis.E1while (expression) statement.E2Its meaning is.E1(a) evaluate the expression(b) if its value is true (i\*.e\*., not zero) do the statement, and go back to (a).E2Because the expression is tested before the statementis executed,the statement part can be executed zero times,which is often desirable.As in the.UL ifstatement, the expression and the statement can both bearbitrarily complicated, although we haven't seen that yet.Our example gets the character,assigns it to.UL c,and then tests if it's a `\\0''.If it is not a `\\0',the statement part of the .UL while is executed,printing the character.The.UL whilethen repeats.When the input character is finally a `\\0',the.UL whileterminates,and so does.UL main\*..PPNotice that we used an assignment statement.E1c = getchar(~).E2within an expression.This is a handy notational shortcut which often produces clearer code.(In fact it is often the only way to write the code cleanly.As an exercise, re-write the file-copy withoutusing an assignment inside an expression.)It works because an assignment statement has a value, just as anyother expression does.Its value is the value of the right hand side.This also implies that we can use multiple assignments like.E1x = y = z = 0;.E2Evaluation goes from right to left..PPBy the way, the extra parentheses in the assignment statementwithin the conditional were really necessary:if we had said.E1c = getchar(~) != '\\0'.E2.UL cwould be set to 0 or 1 depending on whether the character fetchedwas an end of file or not.This is because in the absence of parentheses the assignment operator `='is evaluated after the relational operator `!='.When in doubt, or even if not,parenthesize..PPSince.UL putchar(c)returns.UL cas its function value,we could also copy the input to the output by nesting the calls to.UL getcharand.UL putchar:.E1main(~) { while( putchar(getchar(~)) != '\\0' ) ;}.E2What statement is being repeated?~None, or technically, the.ulnullstatement,because all the work is really done within the test part of the.UL while\*.This version is slightly different from the previous one,because the final `\\0' is copied to the outputbefore we decide to stop..NHArithmetic.PPThe arithmetic operators are the usual `+', `\(mi', `*', and `/'(truncating integer division if the operands areboth.UL int),and the remainder or mod operator `%':.E1x = a%b;.E2sets.UL xto the remainder after.UL ais divided by.UL b(i.e.,.UL a.UL mod.UL b)\*.The results are machine dependent unless.UL aand.UL bare both positive..PPIn arithmetic,.UL charvariables can usually be treated like.UL intvariables.Arithmetic on charactersis quite legal, and often makes sense:.E1c = c + 'A' - 'a';.E2converts a single lower case ascii character stored in.UL cto upper case,making use of the fact thatcorresponding ascii letters are a fixed distance apart.The rule governing this arithmetic is that all.UL charsare converted to.UL intbefore the arithmetic is done.Beware that conversion may involve sign-extension _if the leftmost bit of a character is 1,the resulting integer might be negative.(This doesn't happen with genuine characters on any current machine.).PPSo to convert a file into lower case:.E1main( ) { char c; while( (c=getchar( )) != '\\0' ) if( 'A'<=c && c<='Z' ) putchar(c+'a'-'A'); else putchar(c);}.E2Characters have different sizes on different machines.Further, this code won't workon an IBM machine,because the lettersin the ebcdic alphabet are not contiguous..NHElse Clause; Conditional Expressions.PPWe just used an.UL elseafter an .UL if\*.The most general form of.UL ifis.E1if (expression) statement1 else statement2.E2the.UL elsepart is optional, but often useful.The canonical example sets.UL xto theminimum of.UL aand.UL b:.E1.ne 4if (a < b) x = a;else x = b;.E2Observe that there's a semicolon after.UL x=a\*..PPC provides an alternate form of conditional which is often moreconcise.It is called the ``conditional expression'' because it is a conditionalwhich actually has a valueand can be used anywhere an expression can.The value of.E1a<b ? a : b;.E2is.UL aif.UL ais less than.UL b;it is.UL botherwise.In general, the form.E1expr1 ? expr2 : expr3.E2means``evaluate.UL expr1\*.If it is not zero, the value of the whole thing is.UL expr2;otherwise the value is.UL expr3\*.''.PPTo set.UL xto the minimum of.UL aand.UL b,then:.E1x = (a<b ? a : b);.E2The parentheses aren't necessary because .UL `?:'is evaluated before `=',but safety first..PPGoing a step further,we could write the loop in the lower-case program as.E1while( (c=getchar( )) != '\\0' ) putchar( ('A'<=c && c<='Z') ? c-'A'+'a' : c );.E2.PP.UL If'sand.UL else'scan be used to construct logic thatbranches one of several ways and then rejoins, a commonprogramming structure, in this way:.E1if(\*.\*.\*.) {\*.\*.\*.}else if(\*.\*.\*.) {\*.\*.\*.}else if(\*.\*.\*.) {\*.\*.\*.}else {\*.\*.\*.}.E2The conditions are tested in order,and exactly one block is executed _ either the first one whose.UL ifis satisfied,or the one for the last.UL else\*.When this block is finished,the next statement executed is the one after the last.UL else\*.If no action is to be taken for the ``default'' case,omitthe last.UL else\*..PPFor example, to count letters, digits and others in a file,we could write.E1.ne 9main( ) { int let, dig, other, c; let = dig = other = 0; while( (c=getchar( )) != '\\0' ) if( ('A'<=c && c<='Z') \*| ('a'<=c && c<='z') ) \*+let; else if( '0'<=c && c<='9' ) \*+dig; else \*+other; printf("%d letters, %d digits, %d others\\n", let, dig, other);}.E2The`++' operator means``incrementby 1'';we will get to it in the next section.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -