1

Perhaps better question is, how is it possible that long can store larger numbers than integer, when my compiler tells me that sizeof(int) = sizeof(long) = 4 bytes? I can't wrap my head around it...why wouldn't there be an overflow? Is it adjusted during runtime when there is a need for larger numbers?

Martin
  • 17
  • 2
  • 1
    In C, the size of types such as `int` and `long` can be different on different systems. If `int` and `long` have the same number of bits on your system, then it is not true that `long` can store larger numbers than `int`. – Jesper Dec 14 '18 at 10:28
  • For C99 (and later) you can try `long long` or [`` types](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html): `int_least32_t`, `int_least64_t` – pmg Dec 14 '18 at 10:33
  • The problem is your assumption that `long` can store larger numbers than `int`. That's not necessarily the case. – molbdnilo Dec 14 '18 at 10:39
  • https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models – Maxim Egorushkin Dec 14 '18 at 10:44

1 Answers1

2

According to this:

The standard mandates that int is at least 16 bit, and long is at least 32 bit. So depending on the implementation, it's possible that they're the same size (they could both be 32 bit), or they could be of different sizes. This means that the same program compiled for two different environments may behave differently if it makes assumptions about the size of those data types.

why wouldn't there be an overflow? Is it adjusted during runtime when there is a need for larger numbers?

If for instance you add two integers and store the result in a long, there could indeed be overflow if the long has the same size as the int. That's the problem with those types not having a guaranteed size. If you need such a guarantee, use types like int32_t and int64_t instead, those are guaranteed to be 32 respectively 64 bit.

Blaze
  • 16,736
  • 2
  • 25
  • 44