Functions, parameters, and return values · Funções, parâmetros e valores de retorno
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.
Por que funções
- Uma função é um pedaço nomeado de trabalho. Você a escreve uma vez e a chama sempre que precisar.
- Funções mantêm programas curtos e claros, e permitem construir grandes tarefas a partir de pequenas.
- Você já usou
printf— uma função de<stdio.h>. Agora você escreve a sua própria.
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.
Parâmetros e valores de retorno
- Os valores que você passa são os parâmetros. O valor que você devolve é o valor de retorno.
int max2(int a, int b)recebe doisintparâmetros e retorna umint.return x;encerra a função imediatamente e devolvexpara quem chamou.
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.
Funções void, e construindo grandes a partir de pequenos
- Uma função que não retorna nada tem o tipo de retorno
void. Ela faz trabalho mas não devolve valor. - Uma função pode chamar outra.
max3pode chamarmax2duas vezes para fazer seu trabalho. - Funções pequenas que fazem cada uma uma coisa são mais fáceis de ler e corrigir.
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 copia seus argumentos
- Quando você chama uma função, C dá a ela uma cópia de cada argumento.
- Então alterar um parâmetro dentro da função não altera a variável de quem chamou.
- Mantenha isso em mente — em uma lição posterior, pointers permitem que uma função acesse o original.
#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.
Erros comuns
- Uma função usada antes de ser definida precisa de um protótipo acima de
main. - Argumentos passam por valor — passe um pointer para alterar a variável de quem chamou.
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.
Agora você tenta
- Escreva cada função com o nome exato e parâmetros mostrados, e
returno valor correto. - Você pode chamar uma de suas funções de outra.
- Não escreva um
main— o verificador fornece um.
Functions: call and return · Funções: chamada e retorno
A call pushes a frame with its parameters; return pops it. · Uma chamada empilha um frame com seus parâmetros; return o remove.
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 · chamada max2. Do not · não write a main. · Escreva int max2(int a, int b) retornando o maior de dois números, e int max3(int a, int b, int c) retornando o maior de três. Faça max3 chamar max2. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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 · não write a main. · Complete int power(int base, int exp) para que retorne base elevado a exp (assuma exp >= 0). Use um loop. power(2, 10) é 1024. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int clamp(int x, int lo, int hi) so it keeps x within [lo, hi]: return lo if · se x is below lo, hi if · se x is above hi, otherwise x. Do not · não write a main. · Complete int clamp(int x, int lo, int hi) para manter x dentro de [lo, hi]: retorne lo se x estiver abaixo de lo, hi se x estiver acima de hi, caso contrário x. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.