0

This is a simple problem:

int main()
{

    long int a = 100000;
    long int b = 100000;
    long int c = a*b;
    std::cout << c << std::endl;
}

The output for this (in MSVC) is 1410065408 where one would expect 1 followed by 10 of 0's. I use long ints which the container is large enough for a number of this size if I am not mistaken. Why does this occur?

Silver Flash
  • 871
  • 3
  • 7
  • 16
  • https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-multiply-overflow – Vertexwahn Mar 25 '20 at 08:41
  • 1
    The minimum size of a `long` is a 32 bit type. Windows uses that for example. And that's not large enough for 100000 * 100000. – Bathsheba Mar 25 '20 at 08:42
  • Because signed integer overflow invokes undefined behaviour. Your program might crash, it might appear to work, it might print exactly `1410065408`, it might read you a bedtime story. – George Mar 25 '20 at 08:43
  • oh, I did not realize it was 32 bit on windows. Hmm. – Silver Flash Mar 25 '20 at 08:44
  • Use -fsanitaze=undefined option when compiling. It will check for overflow and other undefined behaviour in runtime (so use it only for testing since it will slow program down) – miszcz2137 Mar 25 '20 at 08:47
  • @miszcz2137 is that option available for gcc? – Waqar Mar 25 '20 at 08:55
  • @SilverFlash even on 64-bit Windows long is still a 32-bit type because Windows uses [LLP64 model](https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models) – phuclv Mar 25 '20 at 09:40
  • 1
    @Waqar It certainly is for gcc, but not sure if windows also (MinGW isn't exactly gcc) – miszcz2137 Mar 26 '20 at 10:16

1 Answers1

1

To find out the limits of integer types on your platform you can use numeric_limits. Results are not the same on different platforms. In your case long is probably a 32 bit integer.

#include <limits>
#include <iostream>

int main() 
{
    std::cout << std::numeric_limits<int>::max() << '\t'
              << std::numeric_limits<long>::max() << '\t'
              << std::numeric_limits<long long>::max() << '\n';
}
hansmaad
  • 18,417
  • 9
  • 53
  • 94