39
Here’s a breakdown of the basic structure of a C program, with explanations and a code example:
1. Preprocessor Directives:
- Lines starting with
#
that instruct the preprocessor to perform tasks before compilation. - Common directives:
#include
: Includes header files containing declarations and definitions.#define
: Defines macros for text substitution.
C
#include <stdio.h> // Include standard input/output library
2. Main Function:
- The entry point of the program, where execution begins.
- It must return an integer value to signal program status.
C
int main() {
// Code to be executed
return 0; // Indicates successful termination
}
3. Variable Declarations:
- Informing the compiler about the variables used in the program and their data types.
C
int age = 25; // Declares an integer variable named age
char initial = 'A'; // Declares a character variable named initial
4. Statements:
- Instructions that perform actions or make decisions.
- Examples:
- Assignment statements (
x = y + 5;
) - Conditional statements (
if
,else
) - Loop statements (
for
,while
) - Function calls (
printf("Hello!");
)
- Assignment statements (
C
printf("Your age is %d.\n", age); // Print a message using printf
5. Comments:
- Non-executable text used for explanations and code clarity.
- Single-line comments:
// This is a comment
- Multi-line comments:
/* This is a multi-line comment */
6. Return Statement:
- Exits the
main
function and optionally returns a value to the operating system.
C
return 0; // Return 0 to indicate successful execution
Code Example:
C
#include <stdio.h>
int main() {
int num1 = 10, num2 = 5;
int sum = num1 + num2;
printf("Sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
Key Points:
- This structure forms a basic template for C programs.
- Indentation and spacing enhance readability.
- Comments are essential for code maintenance and understanding.
- Understanding this structure is crucial for writing well-structured and maintainable C programs.