1

What will hold something like 3000000^2 without overflow?

WhatsInAName
  • 969
  • 2
  • 9
  • 12

4 Answers4

5

3000000^2 is less than 2^48, so an uint64_t from cstdint or stdint.h will hold your number with good margin.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
2

The 64 bit integer:

long long int
unsym
  • 2,080
  • 1
  • 20
  • 19
2

You can check with std::numeric_limits. In c++11, long long is a standard integer of at least 64 bits, so, for example, unsigned long long has these limits:

#include <iostream>
#include <limits>


int main() {
  std::cout << "sizeof : " << sizeof(unsigned long long) << "\n"; 
  std::cout << "min    : "<< std::numeric_limits<unsigned long long>::min() << "\n";
  std::cout << "max    : "<< std::numeric_limits<unsigned long long>::max() << "\n\n";
}

producing on my platform:

sizeof : 8
min    : 0
max    : 18446744073709551615

C++ provides various integer types, but as far as I know the 64 bit types were not mandated by the standard pre-c++11. I long long is the only standard integer to be at least 64 bits, so you would need a compiler with c++11 support. But it could be that your compiler supports some other non-standard 64 bit type.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • I get the following msg: integer constant is too large for "long" type (when I try unsigned long long to store my number) – WhatsInAName Apr 07 '12 at 07:24
  • The problem could be that there was no "standard" 64 bit int before c++11, and maybe your compiler doesn't support c++11? What compiler are you using? – juanchopanza Apr 07 '12 at 07:31
1

When you say "something like", it suggests that you are not actually sure how large the number is that you want to store.

Take a look here (say), and see which numeric type is best for your application.

Note that there is on 64-bit integer in that list; that's because it's not quite available everywhere.

Michael Slade
  • 13,802
  • 2
  • 39
  • 44