Definition of Function
A function in C is a self-contained block of code that performs a specific task. It takes input (arguments), processes it, and optionally returns an output.
Syntax
The general syntax for defining a function is:
return_type function_name(parameter_list) {
// function body
}
For example:
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
Output
add(2, 3)
is called, it returns 5
.
Functions help modularize code, making it more organized and reusable. The main advantage of using functions is that they allow programmers to break complex problems into smaller, manageable pieces, making debugging and testing easier.
Return Values and Their Types
The return type of a function in C specifies the type of value the function will return to the caller. If no return value is required, the function can be defined with a void
return type.
The syntax for a return statement in C is:
return expression;
For example:
int square(int num) {
return num * num; // Returns the square of the number
}
Output: If square(4)
is called, it returns 16
.
Common Return Types
- int: Returns an integer.
- float: Returns a floating-point number.
- char: Returns a single character.
- void: Indicates that the function does not return a value.
Function Calls
A function call executes the function's code. It passes control to the function, optionally providing arguments, and receives the return value if one is specified.
The general syntax for a function call is:
function_name(arguments);
For example:
int result = add(5, 3); // Calls the add function with arguments 5 and 3
Output: result
will contain the value 8
.
Types of Function Calls
- Call by Value: The actual value is passed to the function, meaning changes made to the parameters in the function do not affect the original variables.
- Call by Reference: A reference or address is passed, so changes in the function affect the original variable (not applicable to C but common in languages like C++).
Function Declarations
A function declaration informs the compiler about a function's name, return type, and parameters without providing the actual function code. It allows the function to be used before it is defined, often placed at the beginning of the file.
The general syntax for a function declaration is:
return_type function_name(parameter_list);
For example:
int multiply(int a, int b); // Function declaration
Output: The declaration indicates multiply
takes two integers and returns an integer.
Example Code:
#include <stdio.h>
// Function Declaration (Prototype)
int multiply(int a, int b);
// Main Function
int main() {
int num1 = 4, num2 = 5;
int product = multiply(num1, num2); // Function Call
printf("The product is: %d\n", product);
return 0;
}
// Function Definition
int multiply(int a, int b) { // Parameters (a and b) and Return Type (int)
return a * b; // Returns the product of a and b
}