Can't make printf happy. Rejecting format strings of "i" and "l"

Viewed 163
long int triagedOut = 0;

printf("%i", triagedOut);

main.c|89|warning: format '%i' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]|

I actually get that message twice for the same line. ???

OK, so I will change it to the long int specifier "l" and, then...

printf("%l", triagedOut);

main.c|89|warning: conversion lacks type at end of format [-Wformat=]|

main.c|89|warning: too many arguments for format [-Wformat-extra-args]|

And I get these two messages twice, too.

I don't even know how there could be too many of anything. Just 1 of everything. What's it trying to tell me?

2 Answers

You need to use %ld for long int.

printf("%ld", triagedOut);

Note also these remarks:

  • Format %i indeed expects an int argument, and you are passing a long int, which is a different type and may have a different size, depending on the target platform.

  • Format %l is incomplete: l is just a length modifier, you also need a conversion specifier such as i, d, u, x... hence the proposed correction %ld. i and d are equivalent for printf(), but they have a different meaning for scanf(): %i converts an integer expressed in decimal, octal or hexadecimal as determined by its initial characters, whereas %d only converts an integer expressed in decimal.

     int i;
     sscanf("0x10", "%i", &i);  // sets i to 16
     sscanf("0x10", "%d", &i);  // sets i to 0
     sscanf("010", "%d", &i);   // sets i to 10
     sscanf("010", "%i", &i);   // sets i to 8
    
  • The reason you get the messages twice might be that these are warning messages, not preventing the compilation from proceeding, and your IDE might compile 2 different versions of the executable, one in debug mode and one in production mode.

I think you should use %ld or %li instead of %l or %i for printing long integer.

long int triagedOut = 0;

printf("%li", triagedOut);
Related