Printf was not declared in this scope
The book is outdated.
Add
#include <stdio.h>
to your program. It provides the declaration of printf
and many other functions. For a complete list of functions defined in the file, lookup its documentation.
The compiler didn't find declaration for printf
function. That's why it shows compilation error.
The correct declaration (ISO/IEC 9899:1999) of printf
function is:
int printf(const char * restrictformat, ... );
You can either declare the function like above before calling it or you can include header file
which contains declaration of that function.
But it would be easiest and safest to just include the header file which contains declaration of your function (#include <stdio.h>
for printf
).
If you want to know why you need to supply declaration of the function before calling it, you can have a look at this question. The explanation is given below-
The C programming language was designed so that the compiler could be implemented as a one-pass compiler. In such a compiler, each compilation phase is only executed once. In such a compiler you cannot referrer to an entity that is defined later in the source file.
Moreover, in C, the compiler only interpret a single compilation unit (generally a .c file and all the included .h files) at a time. So you needed a mechanism to referrer to a function defined in another compilation unit. All identifiers in C need to be declared before they are used. This is true for functions as well as variables. For functions the declaration needs to be before the first call of the function. A full declaration includes the return type and the number and type of the arguments. This is also called the function prototype.
You can also define a function before calling it in the same compilation unit. Or you can just declare it before calling it. It is better idea (not always) to include the header file which contains the declaration of the function.
and consider buying a new book. The author should have mentioned the header file inclusion.
printf()
is declared in stdio.h
header file.
Add this as the first line of your program:
#include <stdio.h>