Lesson 25 +10 XP

Format Specifiers with Variables

To print a variable's value, you need to use the format specifier that matches its type.

The pattern


c
int myNum = 15;
printf("%d", myNum);
  • "%d" is the format string.
  • myNum is the value to print.
  • The %d placeholder gets replaced by the value.

Real examples


c
int myNum = 15;                  // %d for int
float myFloatNum = 5.99;         // %f for float
char myLetter = 'D';             // %c for char
double myDouble = 3.14;          // %lf for double

Multiple variables


c
int a = 5;
int b = 10;
printf("%d and %d
", a, b);   // 5 and 10

The placeholders grab the values in order.

Why does it matter?

C is strict: printf %d with a float or the reverse prints garbage. Match the specifier to the type.

TL;DR

  • printf("%d", myNum) prints an int.
  • %f floats, %c chars, %lf doubles.
  • Each % placeholder takes the next argument in order.
  • Mismatched specifiers print garbage.