Branch statement
if statement
Single statement : add a semicolon (;) after any expression;
such as: c = a+b;
compound statement : a statement block enclosed by a pair of curly braces {} is syntactically equivalent to a single statement .
if statement :
if statement is the most commonly used branch statement, also called conditional statement.
if(p!=NULL){
cout << *p <<endl;
}else{
;
}
Note : A better programming specification is that if the curly braces {} are not allowed to be written, even if it is just a single statement;
single branch statement
Double branch statement
Multi-branch statement
switch statement
The general form of
switch : switch (expression)
{ case constant 1: statement 1; break; case constant 2: statement 2; break; … case constant n: statement n; break; default: statement n+1; }
Comparison of switch and if
typedef enum _COLOR
{
RED,
GREEN,
BLUE,
UNKNOW
} COLOR;
COLOR color0;
color0=BLUE;
//if语句
int c0=0
if(color0==RED){
c0+=1;
}
else if(color0==GREEN){
c0+=2;
}
else if(color0==BLUE){
//...
}
//switch语句
switch(color0)
{
case RED:
c0+=1;
break;
case GREEN:
c0+=2;
break;
...
}
//...
scenes to be used
- Switch only supports branch judgments with fixed and equal constant values;
- if can also determine the interval range;
- What can be done with a switch can be done with if, but not the other way around.
Performance comparison
- When there are few branches, the difference is not very big; when there are many branches, the switch performance is higher;
- Several branches at the beginning of if are effective, and then the efficiency decreases;
- The speed of all switch cases is almost the same;