← Exercises|

Printing values, not just text

Write2 of 14 · about 5 min

Printing values, not just text

A format string can contain placeholders. %d means "put a whole number here", %c a single character, %s a string, and %f a number with a decimal point. The values come after the format string, in order.

printf is not told what you passed. If you write %d and hand it a string, it prints whatever it finds — there is no check. Matching the specifier to the type is your job, and it is the source of a good share of C bugs.

This practice runtime tells you when they do not match. A real compiler warns only when it can see the format string at compile time.

Example

#include <stdio.h>

int main(void) {
    int bits = 32;
    char unit = 'b';
    printf("A word is %d %cits wide.\n", bits, unit);
    return 0;
}

prints: "A word is 32 bits wide.\n"

Your task

Declare an int called year set to 1972, and a char called initial set to D. Print exactly: C appeared in 1972, and D stands for Dennis.

  • ·Use the year variable rather than typing 1972 into the text
  • ·Use the initial variable rather than typing D into the text

Stuck?

Explain it

Why does %s fail here when initial holds a character?

Not graded — this is for you.

Where this goes

Project 1 has you print details about the machine you are compiling on. Every one of those is a value with a matching specifier.