C - Program Structure
Explore the foundational structure of a C program, starting with preprocessor directives and the essential main() function. This guide covers global declarations, macros, and user-defined functions, providing insight into how to effectively organize and structure your C code for optimal performance.
C - Program Structure
A C program typically starts with preprocessor directives and must have a main() function. It may also include global declarations, macros, and user-defined functions.
The Preprocessor Section
Header files (with ".h" extension) contain predefined functions. Use #include
to include them in your program.
For example, #include <stdio.h>
is needed for printf() and scanf(). Other common headers are string.h
, math.h
, and stdlib.h
.
Use #define
for constants and macros:
Syntax
#define PI 3.14159
Example with constant:
Syntax
#include
#define PI 3.14159
int main(){
int radius = 5;
float area = PI*radius*radius;
printf("Area: %f", area);
return 0;
}
Output
Area: 78.539749
Example with macro:
Syntax
#include
#define PI 3.14159
#define AREA(r) (PI*r*r)
int main(){
int radius = 5;
float area = AREA(radius);
printf("Area: %f", area);
return 0;
}
Output
Area: 78.539749
The main() Function
Every C program must have a main()
function. It is the entry point of the program.
Example of main()
function:
Syntax
#include
int main() {
printf("Hello, World! \n");
return 0;
}
Output
Hello, World!
The Global Declaration Section
This section contains variable and function declarations that are accessible throughout the program.
Example of global variable declaration:
Syntax
int total = 0;
float average = 0.0;
Example of forward declaration of a function:
Syntax
float area(float height, float width);
Subroutines in a C Program
C programs can have multiple user-defined functions for better organization and reusability.
Comments in a C Program
Comments help document and debug code. They can be multi-line (/* ... */) or single-line (//).
Example of multi-line comment:
Syntax
/*
Program to display Hello World
Author: tutorialsarena
Built with codeBlocks
*/
Example of single-line comment:
Syntax
int age = 20; // variable to store age
Structure of the C Program
Here is an example showing different sections of a C program:
Syntax
/*Headers*/
#include
#include
/*forward declaration*/
float area_of_square(float);
/*main function*/
int main() {
float side = 5.50;
float area = area_of_square(side);
printf ("Side=%5.2f Area=%5.2f", side, area);
return 0;
}
/*subroutine*/
float area_of_square(float side){
float area = pow(side,2);
return area;
}
Output
Side= 5.50 Area=30.25