What will hold something like 3000000^2 without overflow?
-
A 64-bit integer. `unsigned long long` will hold it. – Mysticial Apr 07 '12 at 07:10
-
2So will a `std::string`. – johnsyweb Apr 07 '12 at 07:13
-
I have asked a [related question here](http://stackoverflow.com/questions/10053113/is-c11s-long-long-really-at-least-64-bits). Basically, in c++(11) long long is the only portable way of holding such a number. – juanchopanza Apr 07 '12 at 10:29
4 Answers
3000000^2 is less than 2^48, so an uint64_t
from cstdint
or stdint.h
will hold your number with good margin.

- 176,943
- 25
- 281
- 294
-
For some reason when I try these datatypes, it does not output the correct number. – WhatsInAName Apr 07 '12 at 07:20
-
1@WhatsInAName: Please update your question with some code that demonstrates the problem you are trying to solve. – johnsyweb Apr 07 '12 at 07:21
-
5`^` is the bitwise xor operator. C++ has no exponentiation operator – Keith Thompson Apr 07 '12 at 07:29
-
@WhatsInAName also, could you tell us what compiler you are using and whether it supports some c++11 features? – juanchopanza Apr 07 '12 at 07:36
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.

- 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
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.

- 13,802
- 2
- 39
- 44