Now that you know how functions work, let’s take a closer look at the printf function that you have been using to write to the log.
The printf function accepts a string as an argument and prints it to the log. A string is a “string” of characters strung together like beads on a necklace. Typically, a string is text.
A literal string is text surrounded by double quotes. In the AGoodStart project from Chapter 2, you called printf() with literal string arguments:
// Print the beginning of the novel printf("It was the best of times.n"); printf("It was the worst of times.n");
Your output looked like this:
It was the best of times. It was the worst of times.
You can store a literal string in a variable of type char *:
char *myString = "Here is a string";
This is a C string. You could have created C strings in AGoodStart and passed them to printf():
// Write the beginning of the novel char *firstLine = "It was the best of times.n"; char *secondLine = "It was the worst of times.n"; // Print the beginning of the novel printf(firstLine); printf(secondLine);
Your output would have looked exactly the same.
The printf function can do more than just print literal strings. You can also use printf() to create custom strings at runtime using tokens and variables.
Reopen your ClassCertificates project. In main.c, find congratulateStudent(). Within this function, you call printf() and pass it a string with three tokens and three variables as arguments.
void congratulateStudent(char *student, char *course, int numDays) { printf("%s has done as much %s Programming as I could fit into %d days.n", student, course, numDays); }
When you pass a string containing one or more tokens to printf(), the string that you pass is called the format string. In this example, the format string includes three tokens: %s, %s, and %d.
When the program is run, the tokens are replaced with the values of the corresponding variable arguments. In this case, those variables are student, course, and numDays. Your output looked something like this:
Liz has done as much iOS Programming as I could fit into 5 days.
Tokens are replaced in order in the output: the first variable replaces the first token, and so on. Thus, if you swapped student and course in the list of variables, you would see
iOS has done as much Liz Programming as I could fit into 5 days.
On the other hand, not all tokens and variables are interchangeable. The token you choose tells printf() how the variable’s value should be formatted. The %s token tells printf() to format the value as a string. The %d tells printf() to format the value an integer. (The d stands for “decimal.”)
If you use the wrong token, such as using %d when the substitution is the string "Ted", printf() will try to represent "Ted"
with an integer value, which will give you strange results.
There are other tokens for other types. You will learn and use several more as you continue working through this book.