Flow control

Selection

if else

if (expression1)			
    instruction1;
else if (expression2)			
    instruction2;

else			
    instructionN;

Ternary operator

expr1  ?  inst2  :  inst3

equal to:

if (exp1)			
    inst2
else			
    inst3

switch

switch(expression)
{				
    case constant1:				
        instruction1
        break;

    default :				
        istruzione				
        break;				
}				
  • expression = integer

  • the instruction in a case is executed if expression has the value constant1

  • the default instruction is executed if all the other cases were not executed

Falling Through

Normally (if break is not included), the case block associated with the value of the expression is executed, and then all subsequent case blocks would also be executed.

  • default does not need a break because it's the last expression and would be executed due to fall-through

  • break is included for code symmetry.

Iteration

while

while(expression)
    instruction
  • it repeats the execution of instruction while expression is true

Infinite cycle:

while(1)
    instruction

do while

do		
    instruction		
while(expression)
  • it executes instruction one time

  • in the next iterations, it executes instruction while expression is true

for

for(expr1;expr2;expr3)			
    instruction
  • expr1 = variable initialization

  • expr2 = condition to be checked

  • expr3 = variable value increase/decrease

  • it executes instruction while expr2 is true

  • expr1 can be removed if the inizialization was done outside the cycle

Infinite cycle:

for( ; ; )		
    instruction

Jump

break

It exits from the internal cycle where it is, without verifying the cycle conditions.

continue

  • it jumps to the end of the block cycle, by terminating the current iteration

  • then, it verifies the cycle condition before executing the next iteration

goto LABEL

It jumps to the code block labeled as LABEL:

LABEL:  codice

Comma operator

expr1, expr2
  • expr1 is evaluated

  • expr2 is evaluated

  • the value returned by the , operator is expr1

Last updated