← The C Language
Lesson 27 of 77 · 10 XP
Function parameters
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
In C, arguments are passed by value: the function gets a copy.
void try_change(int x)
{
x = 100; // the copy changes
}
int a = 5;
try_change(a);
printf("%d\n", a); // 5 — the original didn't change
Arrays are an exception — or rather, they only seem to be. When passed to a function, an array turns into a pointer to its first item, so the function works with the original. The size is lost along the way, and it has to be passed separately:
int sum(const int a[], int n) // const is a promise not to change the array
{
int s = 0;
for (int i = 0; i < n; i++)
s += a[i];
return s;
}
sizeof(a) inside such a function returns the size of a pointer, not of the array. It's a common trap.
Task. Write int count_greater(const int a[], int n, int limit) — how many items of the array are greater than limit. In main, read n, n numbers and limit, and print the answer.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.