此函数是否在所有控制路径上都有明确的返回值?

Does this function have explicit return values on all control paths?(此函数是否在所有控制路径上都有明确的返回值?)

本文介绍了此函数是否在所有控制路径上都有明确的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Heaviside 阶跃函数,以任何数据类型的统一为中心,我已经编码使用:

I have a Heaviside step function centered on unity for any data type, which I've encoded using:

template <typename T>
int h1(const T& t){
   if (t < 1){
       return 0;
   } else if (t >= 1){
       return 1;
   }
}

在代码审查中,我的审查者告诉我,并非所有控制路径都明确返回.编译器也没有警告我.但我不同意;条件是互斥的.我该如何处理?

In code review, my reviewer told me that there is not an explicit return on all control paths. And the compiler does not warn me either. But I don't agree; the conditions are mutually exclusive. How do I deal with this?

推荐答案

这取决于模板的使用方式.对于一个 int,你很好.

It depends on how the template is used. For an int, you're fine.

但是,如果 t 是 IEEE754 浮点 double 类型且值设置为 NaN,则两者都不<代码>t <1t >= 1 都是 true ,所以程序控制到达 if 块的末尾!这会导致函数在没有显式值的情况下返回;其行为未定义.

But, if t is an IEEE754 floating point double type with a value set to NaN, neither t < 1 nor t >= 1 are true and so program control reaches the end of the if block! This causes the function to return without an explicit value; the behaviour of which is undefined.

(在更一般的情况下,T 以不覆盖的方式重载 <>= 运算符在所有可能的情况下,程序控制将到达 if 块的末尾,而没有明确的 return.)

(In a more general case, where T overloads the < and >= operators in such a way as to not cover all possibilities, program control will reach the end of the if block with no explicit return.)

这里故事的寓意是决定哪个分支应该是默认的,并将那个分支设为 else 案例.

The moral of the story here is to decide on which branch should be the default, and make that one the else case.

这篇关于此函数是否在所有控制路径上都有明确的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:此函数是否在所有控制路径上都有明确的返回值?

基础教程推荐