Reading Input with scanf (and Defensive Initialization)

Until now, the numbers your program adds are fixed in the code. Every time you want different numbers, you have to edit and rebuild. In this lesson the program asks the user for the numbers instead. Then you make one of the most common beginner mistakes on purpose, and use a simple trick to make it stand out.

In this lesson you will

  • Start a new project by copying the previous one
  • Read numbers from the keyboard with scanf
  • Meet the address-of operator, &
  • Use defensive initialisation to expose a logical error

Before you start: copy your project. Keep 001-FirstCProgram as it is and continue in a copy. That way you can always look back at a working version.

  1. Close the project in Code::Blocks. In File Explorer, copy the 001-FirstCProgram folder and paste it next to the original. Rename the copy 002-UserInputCProgram.
  2. Open the .cbp file inside the new folder. Choose File → Save project as… and save it in the new folder as 002-UserInputCProgram.cbp. Then delete the old 001-FirstCProgram.cbp from the new folder, so you cannot open it by accident.
  3. Open Project → Properties…. On the Project settings tab, change the Title to 002-UserInputCProgram.
  4. On the Build targets tab, change the Output filename for both Debug and Release, for example to bin\Debug\002-UserInputCProgram.exe. If you skip this, your new project still builds a program called 001-FirstCProgram.exe, which gets confusing quickly.

Try it: ask the user for the numbers

Replace main in your new project with the version below. The two scanf lines are new. Notice the & in front of each variable name, and the starting value of -9999. Both are explained shortly.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &y);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Build and run. The program prints the first prompt and then waits. Type 15.1 and press Enter, then type 300 and press Enter:

Please enter a value for x:
15.1
Please enter a value for y:
300
The sum of 15.10 and 300.00 is 315.10

Run it again with different numbers. The program no longer needs rebuilding to add new values.

What just happened

scanf is formatted input, the mirror image of printf. Its first argument is a format string: "%f" means “read the characters the user types and convert them into a float”. Then it needs to know where to put the result.

That is the job of &, the address-of operator. x on its own means “the value inside x”. &x means “the location of x in memory”. printf only needs values to display, but scanf has to change your variable, so you must tell it where the variable lives.

Leave out the & and GCC warns you, and Code::Blocks shows a similar message in its build log:

warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double' [-Wformat=]

Treat that warning as an error and fix it. If you run the program anyway, scanf tries to write to a nonsense location, and the program may crash.

Try it: the copy-paste trap

When you write the second prompt, it is tempting to copy the first two lines, paste them, and change x to y. Now forget to change one of them on purpose. Edit the second scanf so that it still reads into &x:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &x);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Break it on purpose: read y into x

Build the program above: no errors, no warnings. Run it and enter 15.1 and 300 again. Observe:

Please enter a value for x:
15.1
Please enter a value for y:
300
The sum of 300.00 and -9999.00 is -9699.00

The program asked for y, but the 300 went into x and overwrote the 15.1. y was never touched, so it still holds its starting value.

Notice how loudly the mistake shows up. -9999 is not a number anyone would type by accident, so the moment it appears in the output you know a variable was never filled in. Choosing an obviously “impossible” starting value on purpose is called defensive initialisation.

Without it, float y; would contain whatever bits happened to be left in that memory. That value is indeterminate (unpredictable): sometimes zero, sometimes a strange number. A bug that sometimes hides is much harder to find than one that always shouts. Fix the second scanf back to &y, and test again with numbers whose sum you know.

Key terms

  • scanf: reads formatted input from the keyboard and stores it in variables.
  • Address-of operator (&): gives the memory location of a variable, e.g. &x.
  • Initialisation: giving a variable a starting value when you declare it.
  • Defensive initialisation: using a deliberately unusual starting value (such as -9999) so that a variable that is never filled in is easy to spot.
  • Indeterminate value: the unpredictable contents of a local variable that has not been initialised.

Quick check

  1. Why does scanf need &x while printf only needs x?

    Show answer

    scanf has to store a new value in the variable, so it needs the variable’s address. printf only reads the value to display it.

  2. A program prints The sum of 8.00 and -9999.00 is -9991.00. What has most likely gone wrong?

    Show answer

    The second variable was never filled in. Its scanf probably reads into the wrong variable, or is missing.

  3. Does the copy-paste mistake cause a syntax error or a logical error?

    Show answer

    A logical error. The code is valid C, so it builds without warnings, but it does the wrong thing.

  4. After copying a project folder, what two names should you change in Project → Properties?

    Show answer

    The project Title (Project settings tab) and the Output filename of each build target (Build targets tab).

Optional: a recorded demonstration of these steps starts around 0:50. Copying the project to a new folder follows at about 5:20.

Part of the Introduction to C series. Next: Debugging in Code::Blocks: Breakpoints, Step Over, Step Into, Watches

Variables and Format Specifiers: Printing Values with %d

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 int variables
  • Print the value of a variable with the format specifier %d
  • See how printf matches 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 %d that marks where, and how, a value is printed.
  • Logical error: the program builds and runs but produces the wrong result.

Quick check

  1. What does printf("%d minus %d\n", y, x); print when x is 5 and y is 6?

    Show answer

    6 minus 5. The first %d takes the first value listed (y).

  2. 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.

  3. Which line is a declaration with initialisation: int a;, a = 3; or int b = 3;?

    Show answer

    int b = 3;. It declares b and gives it a first value in the same statement.

  4. What happens if a printf has three %d placeholders 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