printf

The printf function is the main way to print out anything in C. The function signature is

int printf(const char *restrict format, ...);

which honestly isn't too helpful to a beginning C programmer.

First of all, ignore the return value. Technically the function can fail, and the return value signals whether it did, but we're going to pretend it never fails.

The first argument is what we call a "format string". It should always be a literal string (i.e. a string you type out with double quotes), not a variable in which you've happened to store a string. By the way, format strings aren't specific to printf - other functions like error use them - but you'll most commonly use them with printf.

You're allowed to put "format specifiers" in format strings. These always start with a percent sign. Here's some common ones:

Format Specifier Type
%d any integer type, printed as a signed base 10 integer
%u any integer type, printed as an usigned base 10 integer
%x any integer type, printed as an usigned hex integer
%s char*, printed as a string
%c char, printed like an English character
%p any pointer type, printed as a hex address
%zu size_t

These are useful because you can supply additional arguments to printf that will be used to replace the format specifiers in the string, one by one.

This is best illustrated by an example. (Note that you can pass variables, not just literals, in the additional arguments!)

printf("The hex number %x is either %d or %u, depending on whether you %s\n", -1, -1, -1, "interpret it as signed or not.");

would print out

The hex number ffffffff is either -1 or 4294967295, depending on whether you interpret it as signed or not.

I also want to point out that I put a \n at the end of my format string. This is good practice so that separate calls to printf end up on separate lines. There's also weird buffering issues where if your program errors out unexpectedly, stuff that should have printed out even before the error don't ever get printed out, which is a huge debugging headache. Just always add \n.