Branch statement in C++

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

Created with Raphaël 2.2.0 开始 表达式? 语句 结束 yes no

Double branch statement

Created with Raphaël 2.2.0 开始 表达式? 语句1 结束 语句2 yes no

Multi-branch statement

Created with Raphaël 2.2.0 开始 表达式1? 语句1 结束 表达式2? 语句2 语句3 yes no yes no

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

  1. Switch only supports branch judgments with fixed and equal constant values;
  2. if can also determine the interval range;
  3. What can be done with a switch can be done with if, but not the other way around.

Performance comparison

  1. When there are few branches, the difference is not very big; when there are many branches, the switch performance is higher;
  2. Several branches at the beginning of if are effective, and then the efficiency decreases;
  3. The speed of all switch cases is almost the same;

Guess you like

Origin blog.csdn.net/yasuofenglei/article/details/108517554
Recommended