HPlogo HP-UX/HP C Compiler: HP C/HP-UX Reference Manual > Chapter 2 Program Organization

Structuring a C Program

» 

Technical documentation

Complete book in PDF

 » Table of Contents

When you write a C program, you can put all of your source code into one file or spread it across many files. A typical C source file contains some or all of the following components:

  • Preprocessor directives

  • Variables

  • Functions

Example 2-1 Example

The following shows how a program can be organized:

/* preprocessor directives */
#include <stdio.h>
#define WEIGHTING_FACTOR 0.6
/* global typedef declaration */
typedef float THIRTY_TWO_BIT_REAL;
/* global variable declaration */
THIRTY_TWO_BIT_REAL correction_factor = 1.15;
/* prototype */
float average (float arg1, THIRTY_TWO_BIT_REAL arg2)
/* start of function body */
{
/* local variable declaration */
float mean;
/* assignment statement */
mean = (arg1 * WEIGHTING_FACTOR) +
(arg2 * (1.0 - WEIGHTING_FACTOR));
/* return statement */
return (mean * correction_factor);
/* end of function body */
}
int main(void)
/* start of function body */
{
/* local variable declarations */
float value1, value2, result;
/* statements */
printf("Enter two values -- ");
scanf("%f%f", &value1, &value2);
result = average(value1, value2);
/* continuation line */
printf("The weighted average using a correction \
factor of %4.2f is %5.2f\n", correction_factor, result);
/* end of function body */
}
© Hewlett-Packard Development Company, L.P.