For integer literals, apart from what's in Bathsheba's answer, it's also used for various cases like suppressing warnings
unsigned int n = somevalue;
...
if (n > 5) dosomething();
Changing to if (n > 5U)
and there'll be no more warnings.
Or when you do something like this
long long x = 1 << 50;
and realized that x is not what you expected, you need to change it to
long long x = 1LL << 50;
Another usage is for the auto
keyword in C++11
auto a = 1;
auto b = 1U;
auto c = 1L;
auto d = 1UL;
The above will result in different types for the variable
For floating-point literals, using suffix will result in more correct result
long double a = 0.01234567890123456789;
long double a = 0.01234567890123456789L;
Those may result in very very different values. That's because a literal without suffix is a double
literal value and will be rounded correctly to double, hence when long double
has more precision than double
it'll result in precision lost. The same will occur with float
s due to double-rounding (first to double then to float, instead of directly round the literal to float)
if (0.67 == 0.67f)
std::cout << "Equal";
else
std::cout << "Not Equal";
The above will print out "Not Equal"
What is the difference between casting to float
and adding f
as a suffix when initializing a float
?