Lesson 4: Basic Structure of a C Program
Understanding the standard components of a C file is crucial for organization.
Key Components
A typical C program structure can be broken down into these parts:
- Documentation Section: Comments describing the program, author, and date.
- Preprocessor Directives: Lines starting with
#(e.g.,#include,#define). - Global Declarations: Variables or functions declared outside of any function.
- The
main()Function: Where execution begins. - User-Defined Functions: Functions written by the programmer to perform specific tasks.
Example Structure
c /* 1. Documentation: Program to calculate area */
// 2. Preprocessor Directive #include <stdio.h>
// 3. Global Declaration #define PI 3.14159
// 5. Function Prototypes (Declarations) float calculate_area(float radius);
// 4. Main Function int main() { float r = 5.0; float area = calculate_area(r); printf("Area: %f\n", area); return 0; }
// 5. Function Definition float calculate_area(float radius) { return PI * radius * radius; }
The Role of main()
The main function is mandatory. Its structure is standardized:
int main(): The simplest form.int main(void): Explicitly states it takes no arguments.int main(int argc, char *argv[]): Used for handling command-line arguments (covered later).
Always ensure your main function returns an integer (usually 0 for success).