I am transitioning from Java to C++ and have some questions about the long
data type. In Java, to hold an integer greater than 232, you would simply write long x;
. However, in C++, it seems that long
is both a data type and a modifier.
There seems to be several ways to use long
:
long x;
long long x;
long int x;
long long int x;
Also, it seems there are things such as:
long double x;
and so on.
What is the difference between all of these various data types, and do they all have the same purpose?
Best Answer
long
andlong int
are identical. So arelong long
andlong long int
. In both cases, theint
is optional.As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that
long long
is at least as wide aslong
.The controlling parts of the standard (C++11, but this has been around for a long time) are, for one,
3.9.1 Fundamental types
, section 2 (a later section gives similar rules for the unsigned integral types):There's also a table 9 in
7.1.6.2 Simple type specifiers
, which shows the "mappings" of the specifiers to actual types (showing that theint
is optional), a section of which is shown below:Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.
Hence
long
on its own is neither a type nor a modifier as your question posits, it's simply a specifier for thelong int
type. Ditto forlong long
being a specifier for thelong long int
type.Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in
1.2 Normative references
, as applying. Hence the minimal ranges as set out inC99 5.2.4.2.1 Sizes of integer types <limits.h>
are applicable.In terms of
long double
, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as adouble
and to provide a superset of values over that type (meaning at least those values, not necessarily more values).