Why isn't `int pow(int base, int exponent)` in the standard C++ libraries?

前端 未结 11 1370
礼貌的吻别
礼貌的吻别 2020-11-27 02:20

I feel like I must just be unable to find it. Is there any reason that the C++ pow function does not implement the \"power\" function for anything except

11条回答
  •  天涯浪人
    2020-11-27 03:08

    That's actually an interesting question. One argument I haven't found in the discussion is the simple lack of obvious return values for the arguments. Let's count the ways the hypthetical int pow_int(int, int) function could fail.

    1. Overflow
    2. Result undefined pow_int(0,0)
    3. Result can't be represented pow_int(2,-1)

    The function has at least 2 failure modes. Integers can't represent these values, the behaviour of the function in these cases would need to be defined by the standard - and programmers would need to be aware of how exactly the function handles these cases.

    Overall leaving the function out seems like the only sensible option. The programmer can use the floating point version with all the error reporting available instead.

提交回复
热议问题