Printing integers with %d and %ld
What you'll learn: How to tell the printf() function whether you are displaying a standard integer or a larger "long" integer.
In C, we use a placeholder called a format specifier to print variables. Think of a format specifier like a reserved seat at a dinner table. You have to tell the computer exactly who is coming to sit there so it can pull out the right size chair.
The standard seat: %d
The most common way to print a whole number (an int) is by using %d. The "d" stands for decimal. When the computer sees %d inside a string of text, it looks at the variable you provided and says, "Okay, I'll treat this as a standard-sized integer."
Standard integers usually handle numbers up to about 2 billion. For most everyday tasks—like counting the number of items in a shopping cart or tracking a player's lives in a game—%d is your go-to tool.
The extra-large seat: %ld
Sometimes, you need to work with much bigger numbers, such as the population of the Earth or the number of bytes on a hard drive. For these, we use the long type.
Because a long takes up more memory (it’s a "longer" number), you cannot use the standard %d. If you try to squeeze a giant long into a small %d seat, the output will be garbled or incorrect. Instead, you use %ld, where the "l" stands for long. It tells the computer to prepare a bigger space to display that larger value.
Seeing it in action
Here is how you use both in a single program:
#include <stdio.h>
int main() {
int score = 500;
long worldPopulation = 8000000000L;
// We use %d for the standard int
printf("The current score is: %d\n", score);
// We use %ld for the long int
printf("The total population is: %ld\n", worldPopulation);
return 0;
}
If you accidentally swap them—using %d for a long—the computer might get confused and print a strange, random-looking negative number because it only "read" half of the data. Always match your specifier to your variable type to keep your data accurate.
Key takeaway
Use %d for standard int variables and %ld for long variables to ensure your numbers print correctly.