C language review and improvement-III. Statements

Source: Internet
Author: User
Tags case statement
III. Statement

A statement is part of an executable program. It indicates an action. Statements in C are classified into the following types:

Select (selection), loop, jump, label, expr, block ).

I. selection statement:

1. If statement: If (expr)/* Processing */;

(1) expr should only generate scalar (INT, Char, float, and _ bool in c99) results.

(2) Try not to use float expressions in expr, because float operations occupy several CPU commands, which will significantly reduce the execution speed. Int or char operations consume less CPU commands.

(3) When nested using the if statement, c89 requires that the compiler should support at least 15 layers of nesting, and c99 should be upgraded to layer 127. In fact, the vast majority of compilers support more than 15 layers.

(4) use? : When the operator replaces the if statement, it is not limited to value assignment. The expression can also contain functions. For example, vrai? F1 (vrai) + F2 (): printf ("error! /N ");/* allow the compiler to reschedule the Value Order when optimizing the target code */

2. Switch statement: Switch (expr) {case... }. It is mainly used to process keyboard input (such as interface menus) and other operations.

(1) expr must evaluate int (Int or char type can be used ).

(2) c89 specifies that a switch statement can contain a maximum of 257 cases, and c99 can be upgraded to 1023. In practice, too many case statements should not be available to improve efficiency.

(3) Switch Feature:-difference from if statement: Switch only tests whether it is equal, and if can test the relationship and logical expression. -The conditions after each case must be different (except for the case statement with the inner and outer layers when nesting ). -The Char constants in the switch statement are all automatically converted to the int type.

Ii. Loop statements: The for loop in C language is the basis for loop statements in all process-oriented languages.

1. For (Init; condition; INC) {/* Processing */}

/** Init is generally a value assignment statement (used to initialize the cyclic variable ). * Condition is a relational expression that specifies the condition for loop exit. * Inc modifies the cyclic variable. ** In a for loop, the condition test is always implemented at the top of the loop (the loop body may not be executed ). */

--> For statement variants:

(1) use of a comma expression: For (init1, init2; condition; INC1, inc2 ){... }

(2) condition does not have to include cyclic variables for some target values. It can be relational or logical statements (multiple possible termination conditions can be tested ). [Example] logon password void user_login () {char passcode [8];/* the UNIX system generally has an 8-bit password, in particular, the old version of NIS is used */INT fois;/* test times */For (fois = 0; fois <3 & strcmp (passcode, "a1b2c3d4"); ++ fois) {printf ("enter the password: -->"); gets (passcode) ;}if (fois = 3) return; /* If the password is incorrect three times, the system returns */else/*. If the password is correct, the user will log on */}

(3) For (expr1; expr2; expr3 ){...} /* The three parts of the for statement can be expressions */

[Example] int I; for (func1 (); I = func2 (); func3 ()) the three parts of the for statement {/* Processing */}/** are function calls. * This is an unconventional but valid method of the for statement. */

(4) the three parts of the for statement can be omitted. The init part is usually defined in vitro, especially when the init part requires complex computing.

[Example] in actual programming, for (;) is often used to implement an endless loop. For (;) {user_input = getchar (); If (user_input = 'q') break;/* The role of break is to force exit the loop */}

(5) null loop: it is mainly used to improve some algorithms or construct a time delay loop ).

[Example 1] style of the China Computer Enthusiast Forum: Remove unnecessary spaces from user input. For (; * STR = ''; STR ++ );

[Example 2] time-consuming, similar to the sleep command in UNIX. For (temps = 0; temps <temps_fixe; temps ++);/* Note that some compilers will optimize the time delay loop */

(6) c99 and C ++ allow declaring variables in the init Part Of The for statement, so that the scope of the loop variable is limited to the block controlled by the statement. For example, for (INT I = 0; I <100; I ++) A + = I;/* in vitro, I is an unknown variable */

2. While loop: While (condition)/* Processing * // * condition can be any non-zero value expression */

(1) While is also a test condition at the top of the loop (the loop body may not be executed ). If any of the conditions can terminate the loop, a loop control variable is usually used to form a condition, and the differences in the loop are assigned a value.

[Example] # define true 1 # define false 0

Void test_while () {int traitement = true; while (traitement) {traitement = proc1 (); If (traitement) traitement = proc2 (); If (traitement) traitement = proc3 ();}}

(2) null loop: [Example] When copying elements in an array to another Array Using a loop: char * From, *; while (* From ++ = * To ++ );

3. Do-while loop: perform a conditional test at the bottom (the loop body must be executed at least once ). Do {/* process */} while (condition );

[Example] A do-while loop is often used to create a menu Subroutine:

Void install ();/* for installing the system */void readme ();/* for reading the readme.txt */

Char selection () {char choice;

Do {Switch (choice = getchar () {Case '1': choice = '1'; break; Case '2': choice = '2'; break; case '3': choice = '3'; break ;}} while (choice! = '1' & choice! = '2' & choice! = '3 ');

Return choice ;}

Void menu () {char resultat;

Printf ("1. install the system. /n "); printf (" 2. read the README file. /n "); printf (" 3. quit. /n ");

Resultat = selection ();

Switch (resultat) {Case '1': Install (); break; Case '2': readme (); break; Case '3': exit (0 ); /* return to OS */}}

Iii. Jump statement: return, break, continue, and goto are the unconditional jump statements of C, where return and goto can be used anywhere in the program, break and continue can be used together with any loop statement.

1. Return Statement: Return to the called point of the function. Return with no value is often returned from void functions.

(1) The number of return operations in a function is not limited, but the execution is stopped immediately when the function is used for the first time, and return to the call point.

(2) void functions cannot use return with a value.

(3) In c89, when a non-void function executes a return without a value, it returns a useless value. This is terrible! In c99 and C ++, a value must be returned for return in a non-void function. (However, if it is executed to the end of a non-void function, a useless value is returned. This is not a syntax error. Try to avoid it .)

2. Break and continue statements:

(1) Two purposes of the break statement: --> end a case in the switch statement. --> If the test is beyond the conventional cycle condition, the cycle is forcibly terminated immediately. (It is often used to terminate a loop immediately according to certain special conditions) [Example] For (INT I = 0; I <100; I ++) if (I = 25) break;

(2) Continue statement: force the next cycle to start. --> For the for statement: continue, the loop starts again from the condition judgment. --> For the while and do-while statements, continue transfers the control to the conditional test.

3. GOTO statement: it is a convenient measure and is often used to jump out of multiple loops. [Example] For (;) {for (;) {/* process */If (/* condition */) goto _ end;/* jump out of all loops directly * // * process */}}}}

_ End:/* label */return;

/** Note the differences with shell programming in UNIX. * The shell script can directly use the Unix Command break 4 to jump out of all the above loops. */

4. # include <stdlib. h> void exit (INT return_code );

/** Standard library function, terminate the program immediately, and return OS. * According to the UNIX System Standard: * If 0 is returned, it indicates normal termination. * if not 0 is returned, it indicates abnormal termination. * Return_code comes with a macro: exit_success and exit_failure ** note the difference between the exit command format and the exit command format in UNIX systems. */

 

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.