The general layout of a simple C program includes the following components:
One or more #include directives to include
header files, which have a filename
ending in ".h". Header files add
functionality that is not part of the C language itself by
defining
named constants such as M_PI
, derived
data types such as FILE
and size_t
,
and the interfaces for all standard library functions.
Header files should never contain executable C statements. Those belong in the C source files (".c" files).
int main(int argc, char *argv[])
{
}
C and C++ are case-sensitive, so PRINTF
is not a
valid substitute for printf
.
Example 16.1. A Simple C Program
/*************************************************************************** * Description: * Compute the area of a circle given the radius as input. * * History: * Date Name Modification * 2013-07-28 Jason Bacon Begin ***************************************************************************/ #include <stdio.h> // Contains prototypes for printf() and scanf() #include <math.h> // Defines M_PI #include <sysexits.h> // Defines EX_OK int main(int argc,char *argv[]) { // Variable definitions for main program double radius, area; // Main program statements printf("What is the radius of the circle? "); scanf("%lf", &radius); if ( radius >= 0 ) { area = M_PI * radius * radius; printf("The area is %f.\n", area); } else fprintf(stderr,"The radius cannot be negative.\n"); return EX_OK; }
#include
is an example of a
preprocessor directive.
#include
inserts a header file
into the program at the point where it appears.
Header files contain constant definitions, type definitions, and
function declarations. Modern C function
declarations are called prototypes, and
they define the interface to the function completely. A prototype
for the printf()
function looks like this:
int printf(const char *format, ...);
The example above contains the function definition
for main()
, the entry point into the program. A
definition begins like a declaration/prototype, but also includes
the function body (the statements that do the work of the function).
C compilers do their job in one pass through the source file, so forward references (references to objects that are declared or defined later) are not allowed. The compiler only needs to see a prototype for functions that is not defined before it is referenced.
The printf()
statement in the example above is a
function call. C programs generally contain
many function calls, since they are used in lieu of language features
that were deliberately left out.
C is a free format language, which means that the compiler treats the end of a line the same as a space or tab. The end of a variable definition or a statement is indicated by a semicolon (;).
What are the major components of a C program?
What is a free-format language?