Defining And Calling Functions.
Lesson 3.1: Defining and Calling Functions
In this lesson, you'll learn how to create your own functions in C. Functions are reusable blocks of code that perform specific tasks, making your programs more organized, efficient, and easier to understand.
Why Use Functions?
Code Reusability: Write code once and use it multiple times, avoiding repetition.
Modularity: Break down a complex program into smaller, manageable parts.
Readability: Make your code easier to understand by giving meaningful names to sections of functionality.
Abstraction: Hide the implementation details of a task and focus on its purpose.
Function Anatomy
A C function typically consists of the following parts:
C
<return type> functionName(parameter1, parameter2, ...) {
// Function body (code to be executed)
return value; // Optional (if the function returns a value)
}
return type: Specifies the type of data the function returns (e.g., int, float, void). If the function doesn't return a value, you use void.
functionName: A descriptive name that indicates what the function does (e.g., calculateSum, displayGreeting).
parameters (Optional): A comma-separated list of variables that hold the values passed into the function.
Function Body: The block of code that performs the function's specific task.
return value; (Optional): If the function returns a value, this statement sends the result back to the caller.
Defining a Function
Let's create a function to calculate the area of a rectangle:
C
#include <stdio.h>
double calculateArea(double length, double width) {
double area = length * width;
return area;
}
In this example:
The return type is double (because the area can be a decimal number).
The functionName is calculateArea.
The parameters are length and width (both of type double).
The function body calculates the area and returns it using the return statement.
Calling a Function
To use a function, you call it by its name and provide any required arguments (values for the parameters):
C
int main() {
double length = 5.0;
double width = 3.0;
double area = calculateArea(length, width); // Call the function
printf("The area of the rectangle is %.2f\n", area);
return 0;
}
Output:
The area of the rectangle is 15.00
Key Points
Function Prototype (Declaration): Before using a function, it's good practice to declare it using a prototype. This tells the compiler the function's name, return type, and parameters.
Function Definition: This is where you write the actual code of the function.
Function Call: This is where you use the function in your code by providing arguments (if needed).
Example: Function Prototype
C
double calculateArea(double length, double width); // Function prototype
int main() {
// ... (rest of the code)
}
// Function definition (can appear after main)
double calculateArea(double length, double width) {
// ... (function body)
}
Let me know if you need help with more concepts or examples.