The first argument to printf()
is always a string value, known as a format control string. This string may be regular text, such as
printf("Hello, World\n"); // \n indicates a newline character
or
char greeting[] = "Hello, World\n";
printf(greeting);
This string may also contain one or more conversion specifiers; these conversion specifiers indicate that additional arguments have been passed to printf()
, and they specify how to format those arguments for output. For example, I can change the above to
char greeting[] = "Hello, World";
printf("%s\n", greeting);
The "%s" conversion specifier expects a pointer to a 0-terminated string, and formats it as text.
For signed decimal integer output, use either the "%d" or "%i" conversion specifiers, such as
printf("%d\n", addNumber(a,b));
You can mix regular text with conversion specifiers, like so:
printf("The result of addNumber(%d, %d) is %d\n", a, b, addNumber(a,b));
Note that the conversion specifiers in the control string indicate the number and types of additional parameters. If the number or types of additional arguments passed to printf()
don't match the conversion specifiers in the format string then the behavior is undefined. For example:
printf("The result of addNumber(%d, %d) is %d\n", addNumber(a,b));
will result in anything from garbled output to an outright crash.
There are a number of additional flags for conversion specifiers that control field width, precision, padding, justification, and types. Check your handy C reference manual for a complete listing.