Does this function have explicit return values on all control paths?

后端 未结 3 1007
[愿得一人]
[愿得一人] 2020-12-08 18:18

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

template 
int h1(const T& t){
   if (t         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 18:48

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

    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.

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

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

提交回复
热议问题