Reputation: 786
So I was doing some testing with the new data type long long when I stumbled upon a little "problem" (example came from C++ Primer 6th edition). I was using the climits library to tell me the maximum number supported by long and long long and both came out to 9223372036854775807. How is that possible?
#include <iostream>
#include <climits>
int main()
{
std::cout << "int size is " << sizeof(int) << " bytes." << std::endl;
std::cout << "short size is " << sizeof(short) << " bytes." << std::endl;
std::cout << "long size is " << sizeof(long) << " bytes." << std::endl;
std::cout << "long long size is " << sizeof(long long) << " bytes." << std::endl;
std::cout << "Maximum values: " << std::endl;
std::cout << "int: " << INT_MAX << std::endl;
std::cout << "short: " << SHRT_MAX << std::endl;
std::cout << "long: " << LONG_MAX << std::endl;
std::cout << "long long: " << LLONG_MAX << std::endl;
return 0;
}
Upvotes: 2
Views: 274
Reputation: 5198
The C99 standard specifies ranges of values each type must be able to represent (§5.2.4.2.1). The specified values are minimum magnitude, so nothing prevent from having bigger range. I converted this value to the least number of bits needed to represent number in these ranges on a digital computer.
int
should be at least 16 bits (range from –32,768 to 32,767)long
should be at least 32 bits (range from –2,147,483,648 to 2,147,483,647)long
long
should be at least 64 bits (range from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)Upvotes: 1
Reputation: 227418
It is possible because the standard mandates that long
has to be at least as large as int
and long long
has to be at least as large at long
(and at least 64 bits in C++11). So there's no contradiction.
Concerning long long
in C++11, see this related question.
Since you tagged the question C++, bear in mind that the numeric limits for a given type are given in the limits
header, and that what is standard in C99 (i.e. what is in <climits>
) is not necessarily standard in C++, i.e. it might be implementation defined. The number of bits in long long
(or, more explicitly, its value range) is an example of a standard in C
that only became standard in C++11.
Upvotes: 5
Reputation: 3509
Because you are running on a 64-bit machine where the compiler implements 'long' and 'long long' as a 64-bit integer.
If you were to compile this on for a 32-bit machine you'd see a difference. For example:
$ g++ -m32 size.cpp
$ ./a.out
int size is 4 bytes.
short size is 2 bytes.
long size is 4 bytes.
long long size is 8 bytes.
Maximum values:
int: 2147483647
short: 32767
long: 2147483647
long long: 9223372036854775807
Upvotes: 5