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.
- Close the project in Code::Blocks. In File Explorer, copy the
001-FirstCProgramfolder and paste it next to the original. Rename the copy002-UserInputCProgram. - Open the
.cbpfile inside the new folder. Choose File → Save project as… and save it in the new folder as002-UserInputCProgram.cbp. Then delete the old001-FirstCProgram.cbpfrom the new folder, so you cannot open it by accident. - Open Project → Properties…. On the Project settings tab, change the Title to
002-UserInputCProgram. - 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 called001-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
Why does
scanfneed&xwhileprintfonly needsx?Show answer
scanfhas to store a new value in the variable, so it needs the variable’s address.printfonly reads the value to display it.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
scanfprobably reads into the wrong variable, or is missing.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.
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