在为微控制器开发代码时,我遇到了这些警告:我的函数有多个return语句。
我可以在功能结束时用单个替换它们,但我认为这更好。有人可以向我解释哪个更好,为什么
unsigned char getDays(unsigned char oldDay,unsigned char newDay,unsigned char currentMonth){
unsigned char xtemp;
if(oldDay < newDay){ //in the same month
xtemp = newDay - oldDay ;
return xtemp ;
}
else{
switch(currentMonth){
case 2:
case 4:
case 6:
case 8:
case 9:
case 0x11:
case 1:
xtemp = newDay + 0x31 - oldDay;
return xtemp ;
break;
case 3:
xtemp = newDay + 0x28-oldDay;
return xtemp ;
break;
case 5:
case 7:
case 0x10:
case 0x12:
xtemp = newDay+0x30-oldDay;
return xtemp ;
}
}
}
答案 0 :(得分:3)
假设所有带有return
语句的路径计算出xtemp
的值,然后用return xtemp;
结束,并且没有循环所以流程是明确的,我建议单个返回声明就足够了。
那就是说,我认为返回语句的数量是该代码中最小的问题。
您的switch语句没有default
子句,因此,如果currentMonth
不是任何选定的case
值,则该函数不会结束(没有return
语句在所有)。如果它使用函数的返回值,则会导致调用者具有未定义的行为。在结尾处使用单个return
语句可以消除该问题,如果代码是结构化的,那么始终初始化xtemp
或为其分配值。
我也会关注可读性 - 一组魔术值,一些表示为十进制,一些表示十六进制,增加了凡人理解代码的难度 - 这反过来又使得更难做对。事实上,我的预感是 - 因为你在至少有一个十进制值似乎是预期的地方使用了十六进制值 - 你实际上没有让这些代码正常工作。
而不是switch
,我可能会使用一些精心构造的if/else if
语句。
答案 1 :(得分:1)
非常感谢您的帮助......在您的帮助下,这是我得到的最终代码
unsigned char getDays(unsigned char oldDay,unsigned char newDay,unsigned char currentMonth){
if (oldDay > newDay){
switch(currentMonth){
case 0x3: return newDay + 0x28 - oldDay;
case 0x5: case 0x7: case 0x10: case 0x12: return newDay + 0x30 - oldDay;
default: return newDay + 0x31 - oldDay;
}
}
return newDay - oldDay; //in the same month
}