Reputation: 70094
I came across a code like below:
#define SOME_VALUE 0xFEDCBA9876543210ULL
This SOME_VALUE
is assigned to some unsigned long long
later.
Questions:
ULL
in this case ?Upvotes: 3
Views: 256
Reputation: 361802
When you don't mention any suffix, then the type of integral literal is deduced to be int
by the compiler. Since some integral literal may overflow if its type is deduced to be int
, so you add suffix to tell the compiler to deduce the type to be something other than int
. That is what you do when you write 0xFEDCBA9876543210ULL
.
You can also use suffix when you write floating-pointer number. 1.2
is a double
, while 1.2f
is a float.
Upvotes: 0
Reputation: 215617
You do not need suffixes if your only intent is to get the right value of the number; C automatically chooses a type in which the value fits.
The suffixes are important if you want to force the type of the expression, e.g. for purposes of how it interacts in expressions. Making it long, or long long, may be needed when you're going to perform an arithmetic operation that would overflow a smaller type (for example, 1ULL<<n
or x*10LL
), and making it unsigned is useful when you want to the expression as a whole to have unsigned semantics (for example, c-'0'<10U
, or n%2U
).
Upvotes: 0
Reputation: 57179
A good example for the use of specifying a suffix in C++ is overloaded functions. Take the following for example:
#include <iostream>
void consumeInt(unsigned int x)
{
std::cout << "UINT" << std::endl;
}
void consumeInt(int x)
{
std::cout << "INT" << std::endl;
}
void consumeInt(unsigned long long x)
{
std::cout << "ULL" << std::endl;
}
int main(int argc, const char * argv[])
{
consumeInt(5);
consumeInt(5U);
consumeInt(5ULL);
return 0;
}
Results in:
INT
UINT
ULL
Upvotes: 2
Reputation: 13520
printf("%ld", SOME_VALUE);
if SOME_VALUE
's integer type is not specified, this might end up with the wrong output.Upvotes: 3
Reputation: 183978
In C, a hexadecimal literal gets the first type of int
, unsigned int
, long
, unsigned long
, long long
or unsigned long long
that can represent its value if it has no suffix. I wouldn't be surprised if C++ has the same rules.
You would need a suffix if you want to give a literal a larger type than it would have by default or if you want to force its signedness, consider for example
1 << 43;
Without suffix, that is (almost certainly) undefined behaviour, but 1LL << 43;
for example would be fine.
Upvotes: 7