Enums

What Are %d and %f Called in C?

%d and %f are format specifiers used by printf and scanf. Learn what each one means in C, how to use them correctly, and how to print enum values.

On this page
  1. The short answer
  2. What %d means
  3. What %f means
  4. A printf example
  5. Using %d and %f with scanf
  6. Printing an enum value
  7. What goes wrong with mismatched specifiers

The short answer

They are called format specifiers, or conversion specifiers. They tell printf and scanf what kind of value to print or read, and how to show it. %d is for integers, and %f is for floating-point numbers.

What %d means

%d expects an int and prints it as a signed decimal number. Use it for whole numbers such as counts, ages, and array indexes.

What %f means

%f prints a floating-point value. By default it shows six digits after the decimal point. When a float is passed to printf, it is converted to double first, so %f works for both types there.

A printf example

#include <stdio.h>

int main(void) {
    int count = 42;
    float price = 9.5f;

    printf("Count: %d\n", count);
    printf("Price: %f\n", price);
    return 0;
}

The output is:

Count: 42
Price: 9.500000

Using %d and %f with scanf

scanf needs the address of the variable it fills in, so you pass &:

int age;
float height;

scanf("%d", &age);
scanf("%f", &height);

For a double, scanf uses %lf. The printf family uses %f for both float and double.

Printing an enum value

An enum value in C is stored as an integer, so %d prints its number:

#include <stdio.h>

enum Color { RED, GREEN, BLUE };

int main(void) {
    enum Color c = BLUE;
    printf("%d\n", c);  // prints 2
    return 0;
}

In C++, an enum class doesn’t convert to int on its own, so cast it first: std::printf("%d\n", static_cast<int>(c));

What goes wrong with mismatched specifiers

If a specifier doesn’t match its argument, the behavior is undefined, so the output can be wrong. For example, printf("%d\n", 9.5); passes a double where %d expects an int. Compilers with -Wall often warn about this kind of mistake.

Printing text uses %s instead. For that side of printf, see what is %s and %d in C?

The complete guide to enums

Enums in C++ With Examples
Read the guide

Keep exploring

Guides from other topics

All topics →

The using Keyword in C++

The using keyword in C++ brings names into scope, creates type aliases and exposes base class members. Here is each form with short examples.

using 5 min read