In the previous lesson you created two variables, x and y, and the compiler warned that you never used them. In this lesson you put them to work. You add them together, print the answer, and then make a mistake that the compiler cannot catch for you.
In this lesson you will
- Declare, assign and initialise
intvariables - Print the value of a variable with the format specifier
%d - See how
printfmatches placeholders to values, in order - Meet your first logical error: a program that builds and runs, but gives the wrong answer
Try it: store and add two numbers
Start from your program from the previous lesson. Below y = 6;, add a third variable that holds the sum, and change the message so that it prints the sum:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5;
int y;
y = 6;
int sum = x + y;
printf("The sum is %d\n", sum);
return 0;
}
The sum is 11
The warnings from the previous lesson have gone, because every variable is now used. Notice that you cannot simply write the word sum inside the quotes. That would print the letters s-u-m. Instead, you leave a placeholder, %d, where the number should go, and pass sum after a comma.
Now change one thing. Make the message more informative by printing all three numbers. Before you build, think about which value lands in which %d:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5;
int y;
y = 6;
int sum = x + y;
printf("The sum of %d and %d is %d\n", sum, x, y);
return 0;
}
Break it on purpose: put the values in the wrong order
Build and run the program above. Observe:
The sum of 11 and 5 is 6
There are no errors and no warnings, and the program ran. But 11 plus 5 is not 6! Before reading on, look at the line of code and work out why the computer printed exactly this.
Now fix it so that the values are listed in the same order as the sentence: x, then y, then sum.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 5;
int y;
y = 6;
int sum = x + y;
printf("The sum of %d and %d is %d\n", x, y, sum);
return 0;
}
The sum of 5 and 6 is 11
What just happened
printf fills its placeholders strictly from left to right. The first %d gets the first value after the string, the second %d gets the second value, and so on. It has no idea what your sentence means. In the broken version the first value was sum (11), so the sentence began “The sum of 11”. The computer did exactly what it was told.
This kind of mistake is called a logical error. The code follows every rule of C, so it builds and runs, but it does not do what you intended. Compare it with the syntax errors from the previous lesson, which the compiler refuses to build. Logical errors are found by testing: work out the answer you expect (5 + 6 = 11) and check that the program agrees.
Break it on purpose: forget a comma
In the fixed program, delete the comma between x and y so that the line ends x y, sum);. Build it:
main.c:10:45: error: expected ')' before 'y'
This time it is a syntax error, and the build fails. A printf call is a string literal followed by a comma-separated list of values, and every value needs its comma. Put the comma back and build again.
Name it: declaring, assigning and initialising
Your program now uses three slightly different ways to create and fill a variable. Each one has a name:
int y;is a declaration. It tells the compiler the variable’s type (int, a whole number) and its identifier (its name,y). No value is given yet.y = 6;is an assignment. It stores a value in a variable that already exists.int x = 5;is a declaration with initialisation. It creates the variable and gives it a first value in one statement.int sum = x + y;also initialises, using the result of a calculation.
A format specifier such as %d tells printf two things: where a value goes in the text, and how to display it. %d means “display an int as a decimal (base-10) whole number”. Other types need other specifiers, which is the subject of the next lesson.
Your turn: start a reference table. Search for the common printf format specifiers and start a table with three columns: data type, specifier, example. Add int → %d now, and keep adding rows as the series goes on.
Key terms
- Variable: a named storage location in memory that holds a value of a particular type.
- Declaration: introduces a variable’s type and identifier, e.g.
int y; - Assignment: stores a value in an existing variable, e.g.
y = 6; - Initialisation: gives a variable its first value when it is declared, e.g.
int x = 5; - Format specifier: a placeholder such as
%dthat marks where, and how, a value is printed. - Logical error: the program builds and runs but produces the wrong result.
Quick check
What does
printf("%d minus %d\n", y, x);print whenxis 5 andyis 6?Show answer
6 minus 5. The first%dtakes the first value listed (y).Is “The sum of 11 and 5 is 6” caused by a syntax error or a logical error? How would you notice it?
Show answer
A logical error. The program builds and runs. You notice it by testing: compare the output with the answer you worked out yourself.
Which line is a declaration with initialisation:
int a;,a = 3;orint b = 3;?Show answer
int b = 3;. It declaresband gives it a first value in the same statement.What happens if a
printfhas three%dplaceholders but only two values after the string?Show answer
GCC warns
format '%d' expects a matching 'int' argument. If you run it anyway, the third number printed is meaningless. Always match each placeholder to one value.
Optional: a recorded demonstration of these steps starts around 33:00.
Part of the Introduction to C series. Next: int vs float: Truncation, Binary, and Choosing the Right Specifier
[…] columns you add. The older notes on decimal to binary show one way to convert. You met integers in Variables, format specifiers, printf %d. Continue with Binary Representation and Manipulation for signed magnitude and two’s complement. […]