Functions, parameters, and return values
Why functions
- A function is a named piece of work. You write it once and call it whenever you need it.
- Functions keep programs short and clear, and let you build big jobs from small ones.
- You have already used
printf— a function from<stdio.h>. Now you write your own.
Зачем нужны функции
- Функция — это именованный фрагмент кода. Вы пишете его один раз и вызываете при необходимости.
- Функции делают программы короче и понятнее, позволяя собирать крупные задачи из мелких.
- Вы уже использовали
printf— функцию из библиотеки<stdio.h>. Теперь вы напишете свою собственную.
Parameters and return values
- The values you pass in are the parameters. The value you hand back is the return value.
int max2(int a, int b)takes twointparameters and returns oneint.return x;ends the function right away and givesxback to the caller.
Параметры и возвращаемые значения
- Значения, которые вы передаете, называются параметрами. Значение, которое вы возвращаете, называется возвращаемым значением.
int max2(int a, int b)принимает два параметра типаintи возвращает одно значение типаint.return x;немедленно завершает функцию и возвращает значениеxвызывающему коду.
void functions, and building big from small
- A function that returns nothing has the return type
void. It does work but hands back no value. - One function can call another.
max3can callmax2twice to do its job. - Small functions that each do one thing are easier to read and to fix.
Функции, не возвращающие значения, и построение сложного из простого
- Функция, которая ничего не возвращает, имеет тип возвращаемого значения
void. Она выполняет работу, но не возвращает результат. - Одна функция может вызывать другую.
max3может вызватьmax2дважды для выполнения своей задачи. - Небольшие функции, выполняющие по одной операции, легче читать и исправлять.
C copies your arguments
- When you call a function, C gives it a copy of each argument.
- So changing a parameter inside the function does not change the caller's variable.
- Keep this in mind — in a later lesson, pointers let a function reach the original.
C копирует ваши аргументы
- При вызове функции C передает ей копию каждого аргумента.
- Поэтому изменение параметра внутри функции не меняет переменную вызывающего кода.
- Имейте это в виду — в более позднем уроке указатели позволят функции обратиться к оригиналу.
#include <stdio.h>
void try_double(int x) {
x = x * 2; // changes only the COPY
}
int main(void) {
int n = 5;
try_double(n);
printf("%d\n", n); // still 5 — the original did not change
return 0;
}
Common mistakes
- A function used before it is defined needs a prototype above
main. - Arguments pass by value — pass a pointer to change the caller's variable.
Распространенные ошибки
- Если функция используется до своего определения, над ней должна быть прототип
main. - Аргументы передаются по значению — чтобы изменить переменную вызывающего кода, передайте указатель.
Now you try
- Write each function with the exact name and parameters shown, and
returnthe right value. - You may call one of your functions from another.
- Do not write a
main— the checker provides one.
Теперь попробуйте сами
- Напишите каждую функцию с точным именем и параметрами, показанными ниже, и верните
returnправильное значение. - Вы можете вызвать одну из ваших функций из другой.
- Не пишите
main— проверяющая система предоставит его.
Functions: call and return
A call pushes a frame with its parameters; return pops it.
Write int max2(int a, int b) returning the larger of two numbers, and int max3(int a, int b, int c) returning the largest of three. Make max3 call max2. Do not write a main.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Complete int power(int base, int exp) so it returns base raised to exp (assume exp >= 0). Use a loop. power(2, 10) is 1024. Do not write a main.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Complete int clamp(int x, int lo, int hi) so it keeps x within [lo, hi]: return lo if x is below lo, hi if x is above hi, otherwise x. Do not write a main.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.