Using a LONG_MAX macro in a printf subroutine

The printf subroutine format string for a 64-bit integer is different than the string used for a 32-bit integer. Programs that do these conversions must use the proper format specifier.

Under LP64, you must also consider the maximum number of digits of the long and unsigned long types. The ULONG_MAX is twenty digits long, and the LONG_MAX is nineteen digits.

In Table 1, the code assumes that the long type is the same size as the int type (as it would be under ILP32). That is, %d is used instead of %ld.

Table 1. Example of using LONG_MAX macros in a printf subroutine
Source:
#include <stdio.h>
int main(void) {
   printf("LONG_MAX( d) = %d\n",LONG_MAX);
   printf("LONG_MAX( x) = %x\n",LONG_MAX);
   printf("LONG_MAX(lu) = %lu\n",LONG_MAX);
   printf("LONG_MAX(lx) = %lx\n",LONG_MAX);
}
LONG_MAX value: 9,223,372,036,854,775,807
Output:
LONG_MAX( d) = -1
LONG_MAX( x) = ffffffff
LONG_MAX(lu) = 9223372036854775807
LONG_MAX(lx) = 7fffffffffffffff
Notes:
  1. Under LP64:
    • %ld must be used
    • %x will give incorrect results and must be replaced by %p or %lx
  2. A similar example would produce the same results for an unsigned long with a ULONG_MAX value of 18,446,744,073,709,551,615.