Tuesday, September 4, 2012

The Structure of C Programs

All C program contain preprocessor directives, declarations, definitions, expressions, statements and functions.

Preprocessor directive The Structure of C Programs

A preprocessor directive is a command to the C preprocessor (which is automatically invoked as the first step in compiling a program). The two most common preprocessor directives are the #define directive, which substitutes text for the specified identifier, and the #include directive, which includes the text of an external file into a program.

The Structure of C Programs

Declaration in C Programs

A declaration establishes the names and attributes of variables, functions, and types used in the program. Global variables are declared outside functions and are visible from the end of the declaration to the end of the file. A local variable is declared inside a function and is visible form the end of the declaration to the end of the function.

Definition of C Programs

A definition establishes the contents of a variable or function. A definition also allocates the storage needed for variables and functions.
Expression
An expression is a combination of operators and operands that yields a single value.
Statement
Statements control the flow or order of program execution in a C program.
Function
A function is a collection of declarations, definitions, expressions, and statements that performs a specific task. Braces enclose the body of a function. Functions may not be nested in C.

main Function
All C programs must contain a function named main where program execution begins. The braces that enclose the main function define the beginning and ending point of the program.

Example: General C program structure

#include <stdio.h> /* preprocessor directive */
#define PI 3.142 /* include standard C header file */
float area; /* global declaration */
int square (int r); /* prototype declaration */
main()
{ /* beginning of main function */
int radius_squared; /* local declaration */
int radius = 3; /* declaration and initialization */
radius_squared = square (radius);
/* pass a value to a function */
area = PI * radius_squared;
/* assignment statement */
printf(“Area is %6.4f square units\n”,area);
} /* end of main function & program */
square(int r) /* function head */
{
int r_squared; /* declarations here are known */
/* only to square */
r_squared = r * r;
return(r_squared); /* return value to calling statement
*/
}

No comments:

Post a Comment