此函数在所有控制路径上都有显式的返回值吗? [英] Does this function have explicit return values on all control paths?

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

问题描述

我有一个 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< 1 t> = 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 块而没有明确的返回。)

(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.

这篇关于此函数在所有控制路径上都有显式的返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆