Functions
Functions
• return_type function_name(parameter_list) {
// body of the function
// code to be executed
}
• return_type: The type of the value returned by the function
(e.g., int, float, void).
• function_name: The name of the function.
• parameter_list: The list of parameters the function takes.
Parameters are optional and can be left empty
• #include <stdio.h>
• // Function declaration (prototype)
• int add(int, int);
• int main() {
• int result = add(5, 3); // Function call
• printf("Result: %d\n", result);
• return 0;
•}
• // Function definition
• int add(int a, int b) {
• return a + b;
•}
January 23, 2025 4
Functions
• Function Declaration (Prototype):
Before using a function in main(), we declare its signature at the top of the
program:
int add(int, int);
This tells the compiler that the function add will take two integers as
parameters and return an integer.
• Function Definition:
The function add is defined after the main() function. It takes two integers
(a and b), adds them, and returns the sum:
int add(int a, int b) {
return a + b;
}
• Function Call:
In the main() function, we call the add function with the arguments 5 and 3:
int result = add(5, 3);
• Return Value:
The function returns the sum, which is stored in the variable result.
January 23, 2025 5
Functions
• Types of Functions
• Standard Functions: Functions that come predefined in the C
library, such as printf(), scanf(), strlen(), etc.
• User-Defined Functions: Functions created by the
programmer to perform specific tasks, like the add function
above.
• void: A function with a void return type does not return any
value.
void printMessage() {
printf("Hello, World!\n");
}
• Non-void: Functions can return values like int, float, char, etc.
int multiply(int x, int y) {
return x * y;
}
Summary:
Pass by Value: The function works with a copy of the argument, and
changes to the parameter do not affect the original argument.
Pass by Reference: The function works with the actual memory
address of the argument, so changes to the parameter affect the
original argument.