0
#include <iostream>
using namespace std;


int power(int baseNum, int powNum){
   int result = 1;
   for(int i = 0; i < powNum; i++){
     result = result * baseNum;
   }
   return result;
}
int main()
{
    cout << power(10, 94);

    return 0;
}

Why does this turn out 0 in code::blocks? Is it that the system memory is too small? I have 8 GB of RAM on my laptop.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • Unrelated, but you may want to read [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/11082165) – Brian61354270 Sep 05 '21 at 19:50
  • 3
    It looks like you don't have a basic knowledge of how most languages handle integers. It has nothing to do with how much memory you have. 32-bit integer will fit 32-bit sized values, a 64-bit int will fit 64-bit sized value, etc. If you want arbitrary sized integers that go beyond 32-bit, 64-bit, etc., that requires you to write the code to implement such ints and/or use one of the many "big integer" libraries available for C++. – PaulMcKenzie Sep 05 '21 at 19:51
  • 3
    Both GCC and Clang catch this with `-fsanitize=undefined`: _runtime error: signed integer overflow: 1000000000 * 10 cannot be represented in type 'int'_ – chris Sep 05 '21 at 19:51
  • This is integer overflow. Limit is `2^31 - 1` which is much much less then `10^94`. Since this is signed type behavior is undefined. https://godbolt.org/z/PY9bcG7K1 – Marek R Sep 05 '21 at 19:52
  • Related: [maximum value of int](https://stackoverflow.com/q/1855459/11082165) and [Is signed integer overflow still undefined behavior in C++?](https://stackoverflow.com/q/16188263/11082165) – Brian61354270 Sep 05 '21 at 19:53
  • Why do you need this? I suspect you are solving some online problem (or homework) and your approach is to simple. – Marek R Sep 05 '21 at 19:56
  • While same have noticed, this is technically undefined behavior from the Standard, in practice this is well defined on all modern CPU architectures which do modulo 2^32 arithmetic. Multiplying by ten means multiplying by 5 (0b101) and by 2, which is shift left. So the result would end with 94 bits at 0. The 32 lower bits of that theoretcal result being all 0, you observe the result of **0**. – prapin Sep 05 '21 at 19:58
  • You would need an integer type with around 314 bits to represent 10^94. – Adrian Mole Sep 05 '21 at 20:02
  • @prapin [GCC disagrees.](https://godbolt.org/z/91K1xdoWs) – danielschemmel Sep 05 '21 at 23:14
  • Thank you, I did not have basic knowledge of how most languages handle integers. I will try my best to implement some of those "big integer" libraries for C++. – Axel Sprängare Sep 11 '21 at 12:52

0 Answers0