0

Question What does the "L" mean at the end of an integer literal? describes what L means at the end of int literal. I am confused why not to specify long int i = 33 instead of int i = 33L? The same thing applies to other types. Instead of specifying double b = 3.0L why not to write long double?

ty452567
  • 51
  • 3
  • http://en.cppreference.com/w/cpp/language/integer_literal – user0042 Dec 06 '17 at 16:06
  • Sometimes you are not assigning to a variable, but using it as a term in an expression. This can be used to force a widening conversion, for example. – cdhowie Dec 06 '17 at 16:07
  • If you're using `auto` instead of a specific type, the literal will deduce to the correct type. – user0042 Dec 06 '17 at 16:08
  • 1
    `int i = 33L` is not declaring a `long int`. It is declaring an `int` that is initialized with a sloppy narrowing cast. – Silvio Mayolo Dec 06 '17 at 16:09
  • Possible duplicate of [what is the reason for explicitly declaring L or UL for long values](https://stackoverflow.com/questions/13134956/what-is-the-reason-for-explicitly-declaring-l-or-ul-for-long-values) – phuclv Dec 06 '17 at 16:13
  • [Why do you need to append an L or F after a value assigned to a C++ constant?](https://stackoverflow.com/q/1380653/995714), [Are long-suffix and unsigned-suffix needed when declaring long literals in C++?](https://stackoverflow.com/q/975942/995714) – phuclv Dec 06 '17 at 16:15

2 Answers2

2

I am confused why not to specify long int i = 33 instead of int i = 33L?

Because that 2 statements mean 2 different things:

long int i = 33; // take constant of type int, convert it to long int and assign to i.

int i = 33L; // take constant of type long int, convert it to int and assign to i.

So you end up with variable i of different type. Same for the double in your example.

Slava
  • 43,454
  • 1
  • 47
  • 90
1

Although in many instances, you can rely on the extremely well-defined widening conversion rules, sometimes you need to be explicit about the type of a literal.

For example

long double f = 1.0;
f = std::max(f, 2.0L);

does not compile unless the arguments of max have the same type. Writing double b = 3.0L would indeed be pointless, and a compiler will almost certainly ignore you and compile double b = 3.0.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483