今天看到了一段充满if else 的代码
void NVIC_Init(NVIC_InitTypeDef *NVIC_InitStruct)
{
uint8_t tmppre = 0;
if(NVIC_Priority_Group == NVIC_PriorityGroup_0)
{
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, NVIC_InitStruct->NVIC_IRQChannelSubPriority << 4);
}
else if(NVIC_Priority_Group == NVIC_PriorityGroup_1)
{
if(NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority == 1)
{
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (1 << 7) | (NVIC_InitStruct->NVIC_IRQChannelSubPriority << 4));
}
else
{
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (0 << 7) | (NVIC_InitStruct->NVIC_IRQChannelSubPriority << 4));
}
}
else if(NVIC_Priority_Group == NVIC_PriorityGroup_2)
{
if(NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority <= 1)
{
tmppre = NVIC_InitStruct->NVIC_IRQChannelSubPriority + (4 * NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority);
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (0 << 7) | (tmppre << 4));
}
else
{
tmppre = NVIC_InitStruct->NVIC_IRQChannelSubPriority + (4 * (NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority - 2));
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (1 << 7) | (tmppre << 4));
}
}
else if(NVIC_Priority_Group == NVIC_PriorityGroup_3)
{
if(NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority <= 3)
{
tmppre = NVIC_InitStruct->NVIC_IRQChannelSubPriority + (2 * NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority);
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (0 << 7) | (tmppre << 4));
}
else
{
tmppre = NVIC_InitStruct->NVIC_IRQChannelSubPriority + (2 * (NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority - 4));
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, (1 << 7) | (tmppre << 4));
}
}
else if(NVIC_Priority_Group == NVIC_PriorityGroup_4)
{
NVIC_SetPriority(NVIC_InitStruct->NVIC_IRQChannel, NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority << 4);
}
if(NVIC_InitStruct->NVIC_IRQChannelCmd != DISABLE)
{
NVIC_EnableIRQ(NVIC_InitStruct->NVIC_IRQChannel);
}
else
{
NVIC_DisableIRQ(NVIC_InitStruct->NVIC_IRQChannel);
}
}
然后我思考了这个问题?
是不是可以选择用switch case 缓解众多if elseif 造成的焦虑?
在确定你想使用switch/case或者 if/elseif语句时,很重要的一点是明确使用哪一种才能达到最高的性能。
我推荐使用下面的指南来帮助你选择:
如果已有条件比较相关,switch / case可以是更快更明确的选择
如果你想检查多个不关联的条件,if / elseif可以是最好的选择
如果条件之间存在逻辑上的分歧,同样优先使用if/elseif
如果意图在代码中不明显, if / elseif的结构也可以很容易的进行修改
使用 switch / case 语句会显著减少代码量
如果你想测试和比较相同数据类型的值(如字符串和数字),使用 switch / case 能够控制一些例外情况并提高可读性
|
有点看晕了,可以解答一下吗