passing arguments and returning value from a function
Learn passing arguments and returning value from a function step by step with clear examples and exercises.
Why This Matters
Understanding how to pass arguments and return values from functions is essential for writing efficient C programs. It allows you to create modular, reusable code that can be easily tested and maintained. This concept is crucial for solving complex problems, preparing for coding interviews or exams, and understanding real-world programming scenarios.
Prerequisites
Before diving into passing arguments and returning values from functions, you should have a good understanding of:
- Basic C syntax and data types (e.g.,
int,char,float) - Variables and their scope
- Control structures like
ifstatements and loops - Arrays and pointers
Core Concept
A function in C is a self-contained block of code that performs a specific task. Functions can take inputs (arguments) and return outputs (values). To pass arguments to a function, you use the parameter list within the function definition. To return a value from a function, you use the return statement.
Function Definition
A function is defined using the following syntax:
return_type function_name(parameter1 type parameter1_name, ...) {
// function body
}
return_typespecifies the data type of the value that the function returns. If a function doesn't return any value, its return type isvoid.function_namegives a unique name to the function.parameter1 type parameter1_namedeclares a formal parameter for the function. You can have multiple parameters separated by commas.- The curly braces
{ ... }enclose the code that makes up the function body.
Calling a Function
To call a function, you use its name followed by parentheses containing any necessary arguments:
function_name(argument1, argument2, ...);
- The actual arguments passed to the function must match the data type and number of parameters declared in the function definition.
- If a function doesn't take any arguments, you can still call it without providing any arguments within the parentheses.
Passing Arguments by Value
By default, C passes arguments to functions by value. This means that the function receives a copy of the original variable, and changes made within the function do not affect the original variable. To demonstrate this, consider the following example:
void increment(int x) {
x = x + 1;
}
int main() {
int num = 5;
printf("Initial value of num: %d\n", num);
increment(num);
printf("Value of num after calling increment: %d\n", num);
return 0;
}
In this example, the increment function takes an integer argument and increments its value by 1. However, since arguments are passed by value, the original variable num in the main function remains unchanged. The output of this program will be:
Initial value of num: 5
Value of num after calling increment: 5
Passing Arguments by Reference (using pointers)
To allow a function to modify the original variable, you can pass arguments by reference using pointers. To create a pointer, use the address-of operator &. In the function definition, declare the parameters as pointers by prefixing them with an asterisk *. Here's an example:
void increment_ptr(int *ptr) {
*ptr = *ptr + 1;
}
int main() {
int num = 5;
printf("Initial value of num: %d\n", num);
increment_ptr(&num);
printf("Value of num after calling increment_ptr: %d\n", num);
return 0;
}
In this example, the increment_ptr function takes a pointer to an integer and increments its value. Since we're passing the address of the original variable num, changes made within the function will affect the original variable. The output of this program will be:
Initial value of num: 5
Value of num after calling increment_ptr: 6
Returning a Value from a Function
To return a value from a function, use the return statement followed by the desired value. The function must have a return type that matches the data type of the returned value. Here's an example:
int get_sum(int x, int y) {
int sum = x + y;
return sum;
}
int main() {
int num1 = 3;
int num2 = 5;
int result = get_sum(num1, num2);
printf("Sum of num1 and num2: %d\n", result);
return 0;
}
In this example, the get_sum function takes two integer arguments and returns their sum. The returned value is then assigned to the variable result in the main function and printed. The output of this program will be:
Sum of num1 and num2: 8
Worked Example
Let's create a function that swaps two integers passed as arguments using pointers:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 3;
int num2 = 5;
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
In this example, the swap function takes two pointers to integers and uses them to swap the values of the original variables. The output of this program will be:
Before swapping: num1 = 3, num2 = 5
After swapping: num1 = 5, num2 = 3
Common Mistakes
Forgetting to return a value from a function that should return one
Ensure that you use the return statement with the appropriate data type when needed. If a function is supposed to return a value but doesn't, it will cause issues in the calling code.
Not using parentheses when calling a function with multiple arguments
Always use parentheses when calling a function with multiple arguments to avoid confusion and ensure proper syntax.
Passing arguments by value when you need to pass them by reference (or vice versa)
Be mindful of whether you want the function to modify the original variable or not, and adjust your code accordingly by using pointers or passing values directly.
Practice Questions
- Write a function that swaps two integers passed as arguments without using pointers.
- Write a function that calculates the factorial of a given number recursively.
- Write a function that finds the maximum of three integers passed as arguments using if-else statements.
- Write a function that checks whether a given number is prime or not.
- Write a function that sorts an array of integers using bubble sort.
FAQ
Why can't I pass arrays directly to functions in C?
In C, you cannot pass arrays directly to functions because the function would only receive a copy of the array's address, not the actual array. To work around this limitation, you can use pointers to pass arrays as arguments.
What happens if I don't return a value from a function that should return one?
If a function is supposed to return a value but doesn't, it will typically cause an error or undefined behavior when the returned value is used in the calling code. In some cases, the compiler may implicitly return 0 or NULL instead.