C Function Parameters
Parameters are the variables a function receives; arguments are the values you give when you call it. In int add(int a, int b), a and b are parameters; in add(2, 3), 2 and 3 are the arguments.
Several parameters
Parameters are separated by commas, each with its own type. The arguments are matched by position.
#include <stdio.h>
void introduce(const char *name, int age) {
printf("%s is %d years old.\n", name, age);
}
int main(void) {
introduce("Asha", 12);
introduce("Ravi", 14);
return 0;
}Asha is 12 years old. Ravi is 14 years old.
const char *name is how a function receives a string it will only read; const promises it will not change it.
Pass by value
C always passes a copy of each argument. Changing the parameter inside the function does not change the caller's variable:
#include <stdio.h>
void tryToChange(int n) {
n = 100;
printf("inside: n = %d\n", n);
}
int main(void) {
int n = 5;
tryToChange(n);
printf("outside: n = %d\n", n);
return 0;
}inside: n = 100 outside: n = 5
To let a function change a variable, pass its address and use a pointer parameter, as swap does in the Pointers topic. A function can also simply return a new value, which is often clearer.
Passing arrays
When an array is passed, the function receives a pointer to its first element, not a copy. That has two consequences: the function can change the array's elements, and it cannot know the array's length, so the length is passed too.
#include <stdio.h>
int total(const int values[], int count) {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += values[i];
}
return sum;
}
void doubleAll(int values[], int count) {
for (int i = 0; i < count; i++) {
values[i] *= 2;
}
}
int main(void) {
int marks[] = {10, 20, 30, 40};
int n = sizeof(marks) / sizeof(marks[0]);
printf("total: %d\n", total(marks, n));
doubleAll(marks, n);
printf("after doubling: %d %d %d %d\n", marks[0], marks[1], marks[2], marks[3]);
return 0;
}total: 100 after doubling: 20 40 60 80
const int values[] documents that total only reads the array; the compiler stops any attempt to change it.
Returning more than one result
A function returns at most one value. For two results, return one and pass a pointer for the other, or pass pointers for both:
#include <stdio.h>
void minMax(const int a[], int n, int *min, int *max) {
*min = *max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *min) *min = a[i];
if (a[i] > *max) *max = a[i];
}
}
int main(void) {
int a[] = {7, 2, 9, 4};
int lo, hi;
minMax(a, 4, &lo, &hi);
printf("min %d, max %d\n", lo, hi);
return 0;
}min 2, max 9
Practice exercises
- Write
void printArray(const int a[], int n)and use it to print two different arrays. - Write a function that divides two integers and returns both the quotient and the remainder through pointers.
- Write
void reverse(int a[], int n)that reverses an array in place.