1

In K&R (second edition) in section 4.9 (pg. 85) when discussing Initialization, an example of calculating the number of milliseconds in a day is given:

long day = 1000L * 60L * 60L * 24L

Why are long literals used here on the RHS of the assignment? In section 2.7 (Type Conversions) on pg 44 the following rules are given:

If either operand is long double, convert the other to `long double

Otherwise if either operand is double , convert the other to double

Otherwise if either operand is float, convert the other to float

Otherwise, convert char and short to int

Then, if either operand is long, convert the other to long.

For the calculation of long day = ..., surely int literals could be used here? Would they not automatically be converted to long based on the rules above?

I wrote the following:

long day1 = 1000L * 60L * 60L * 24L;

long day2 = 1000*60*60*24;

Within the debugger, both day1 and day2 were long. What was the purpose of using long literals?

Nate
  • 11
  • 2

2 Answers2

2

1000*60*60*24 is done using int math which may overflow when int is 16-bit.

1000L * 60L * 60L * 24L does not overflow as long is at least 32-bit.


Code could have been as below to achieve long math with all the Ls.

long day = 1000L * 60 * 60 * 24;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

In standard C, an int is only guaranteed to hold 16 bit values, while a long is guaranteed to hold 32 bit values.

K&R predates standard C, but the standard derives from the rules that K&R had in place. So long is required to guarantee the value will fit.

dbush
  • 205,898
  • 23
  • 218
  • 273