c++integerliteralssuffix

Why are there type modifiers for constants?


I can not understand what the purpose is of type modifiers for literal constants, like for numerical constants:

75 
75u     
75l  
75ul
75lu 

In what cases could this possibly be useful? I mean if you already have declared a type modifier for the variable type, I do not see a need for this. If anybody could help me understand this, it would be amazing! Thanks!

Bonus question: Is "literal" the same as "constant" like could you just say "literal" instead of "literal constant"?


Solution

  • 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 floats 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?