unsigned long long int pow

前端 未结 2 858
心在旅途
心在旅途 2021-01-13 11:34

I have the following power function which operates on integers and it works fine:

int ipow( int base, int exp )
{
    int result = 1;
    while( exp )
    {
         


        
相关标签:
2条回答
  • 2021-01-13 12:06

    Section 6.5p4 of the C standard:

    Some operators (the unary operator ~, and the binary operators <<, >>, &, ^, and |, collectively described as bitwise operators) are required to have operands that have integer type. These operators yield values that depend on the internal representations of integers, and have implementation-defined and undefined aspects for signed types.

    Section 6.5p5 of the C standard:

    If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

    If it seemed like a good idea to use int in this code before, it shouldn't now. Both of these sections are saying that your code isn't as portable as it could be.

    0 讨论(0)
  • 2021-01-13 12:15

    Your base variable is too small. Change it to unsigned long long int, like the others, since it holds numbers greater than 2^32.

    0 讨论(0)
提交回复
热议问题