Why are there type modifiers for constants?

I can't seem to figure out what the purpose of the type modifiers for a literal is, as for numeric constants:

75 
75u     
75l  
75ul
75lu 

      

When can this be useful? I mean, if you've already declared a type modifier for the type of a variable, I don't see the need for that. If anyone could help me figure this out, that would be awesome! Thank!

Bonus question: "Literal" is the same as "constant", how could you just say "literal" instead of "literal constant"?

+3


source to share


3 answers


For integer literals, besides being in Batsheva's answer, it is also used for various cases such as suppressing warnings

unsigned int n = somevalue;
...
if (n > 5) dosomething();

      

Go to if (n > 5U)

, and there will 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;

      

Other use for a keyword auto

in C ++ 11



auto a = 1;
auto b = 1U;
auto c = 1L;
auto d = 1UL;

      

The above will result in different types of variable

For floating point literals, using a suffix will produce a more correct result

long double a = 0.01234567890123456789;
long double a = 0.01234567890123456789L;

      

Those can have very different meanings . This is because a literal without a suffix is โ€‹โ€‹a literal value double

and will be rounded correctly to double, so when it long double

has greater precision than double

it will result in a loss of precision. The same will happen with float

due to double-rounding (first for double and then for float, not directly rounding to literal value for float)

if (0.67 == 0.67f)
   std::cout << "Equal";
else 
   std::cout << "Not Equal";

      

The above version will print "Not Equal"

What is the difference between casting to float

and adding f

as a suffix on initialization float

?

+3


source


Sometimes a literal must be of a specific type. for example

void foo(const int&){
    // pay myself
}

void foo(const unsigned&){
    // reformat my disk
}

      



Then foo(75)

they foo(75u)

will have very different results.

Infact, this is so useful that it is possible to define your own literals from C ++ 11. See http://en.cppreference.com/w/cpp/language/user_literal

+8


source


One of the most common times I see this is in 75ul << 18

. The input to the shift must have enough bits to make this shift. 75

could be 16 bits, which makes the shift more than 18 bits Undefined Behavior (bad). 75ul

is at least 32 bits.

0


source







All Articles