Structure of a C program
C program typically consists of several elements, organized in a specific structure. Here's an overview of the typical structure of a C program:
Preprocessor Directives: These are lines that start with a hash symbol (#) and provide instructions to the preprocessor, which performs various tasks before the actual compilation. Preprocessor directives includes header files, defining macros, and conditional compilation instructions.
Header Files: These files contain function prototypes, type definitions, and macro definitions used in the program. They are included in the program using the preprocessor directive "#include".
Function Declarations: In C, you need to declare the functions you use before calling them. Function declarations specify the return type, name, and parameters (if any) of a function. Function declarations usually go before the main() function.
Main Function: The main() function is the entry point of a C program. It is where the execution of the program starts. Every C program must have a main() function. It has a return type of int and can have command-line arguments passed as parameters.
Variable Declarations: In C, variables must be declared before they can be used. Variable declarations specify the type and name of variables. They can be placed at the beginning of a function or within blocks of code.
Statements and Expressions: Statements are individual instructions that perform specific tasks. They can include variable assignments, function calls, conditional statements (if-else, switch), loops (for, while, do-while), and more. Expressions are combinations of values, variables, and operators that evaluate to a result.
Function Definitions: After the main() function, you define the functions that you declared earlier. Function definitions include the actual implementation of the functions, specifying the return type, name, parameters, and the code block that defines the function's behavior.
Comments: Comments are used to document the code and provide explanations. They are not executed by the compiler and are meant for programmers to understand the code better. C supports both single-line comments (starting with //) and multi-line comments (enclosed between /* and */).
Here's a basic example illustrating the structure of a C program:
In this example, the program includes the <stdio.h> header file for input/output functions, declares the addNumbers() function, defines the main() function, declares and initializes variables, calls the addNumbers() function, and prints the result using printf().