Anol's answer is very on-point and I believe is the most correct assessment as to why int pow()
is not a part of the standard library, however I would like to amend it with another possibility.
The most useful aspect of the pow
function is the ability to correctly (at least as far as floating point arithmetic is concerned) perform exponentiation to non-integer powers. This type of behavior is non-trivial to implement using integer math, let alone floating point math. Rather than asking library implementors to write both an integer exponentiation routine and a floating point exponentiation routine, they decided to ask for the more useful of the two. It also helps that the x87 instruction set, as well as many other FPU instruction sets, provides built-in floating point exponentiation instructions to make the implementation on the software side trivial.
C also doesn't have any notion of exceptions, and no language-level global state that could expose things like CPU flags. This would make overflow detection in an int pow()
implementation difficult to provide. In the case of double pow()
, it can just return a non-signalling NaN
or Infinity
in the case of exceptional circumstances. However there is no notion of NaN
or Infinity
in the integer world.
In the case of an exception, the program could do one of the following:
- Overflow Silently
- Return
INT_MIN
or INT_MAX
- Change an integer whose pointer was provided to the function by the caller
- Change some global state like
errno
- Emit a
SIGFPE
- Provide a sister function
int pow_overflow_check()
that can be used to boilerplate the call
None of these are desirable. The first two options would lead to hard-to-diagnose logic errors in possibly unrelated areas of a program. The third one would provide an annoying and cumbersome barrier to the use of the function. The fourth one would ruin any sort of reentrancy guarantee. The fifth option would make the entire program grind to a halt. The sixth option would work well, but would also bloat the standard more, and make the function more cumbersome to use like in the third option.
Further, just like others have stated, exponentiation to an integer power, especially if the base is 2, is trivial to implement. A first year compsci student with a basic understanding of math should be able to formulate a correct implementation that could suit most use cases.
The original C language was aimed squarely at assembly programmers, and this is one of the symptoms of that. A very common theme in the language spec is that the language library should only provide things that are either impossible to implement in-language in a portable manner, or extremely non-trivial to implement purely in-language, especially when there are commonly available CPU/FPU instructions that can do it for you.