Procedures, functions and structured programming · Procedimentos, funções e programação estruturada
| English | Português |
|---|---|
| subroutines/ˈsʌbruːtiːnz/ | subrotinas |
| function/ˈfʌŋkʃn/ | função |
| procedure/prəˈsiːdʒə/ | procedimento |
| structured programming/ˈstrʌktʃəd ˈprəʊɡræmɪŋ/ | programação estruturada |
| decomposition/ˌdiːkɒmpəˈzɪʃn/ | decomposição |
| parameters/pəˈræmɪtəz/ | parâmetros |
| arguments/ˈɑːɡjuːmənts/ | argumentos |
| signature/ˈsɪɡnɪtʃə/ | assinatura |
| pass by value/pæs baɪ ˈvæljuː/ | passagem por valor |
| pass by reference/pæs baɪ ˈrefrəns/ | passagem por referência |
| global variable/ˈɡləʊbl ˈveərɪəbl/ | variável global |
| local variable/ˈləʊkl ˈveərɪəbl/ | variável local |
| scope/skəʊp/ | escopo |
A tape of routines anyone could borrow
- By 1951 the EDSAC team in Cambridge kept a library of subroutines on punched paper tape: square roots, printing, logarithms. Any program could read one in and call it.
- The hard part was getting back. David Wheeler's trick, the "Wheeler jump", stored the return address so a routine could return to wherever it had been called from.
- Every function call you write today does the same thing, and every language library descends from that tape.
- This lesson is procedures and functions: how to define them, how to pass values in and out, and how to write one the way Paper 2 marks it.
Uma fita de rotinas que qualquer um poderia pegar emprestado
- Em 1951, a equipe EDSAC em Cambridge mantinha uma biblioteca de subrotinas em fita de papel perfurada: raízes quadradas, impressão, logaritmos. Qualquer programa podia ler um deles e chamá-lo.
- A parte difícil era voltar. O truque de David Wheeler, o "Wheeler jump", armazenava o endereço de retorno para que uma rotina pudesse retornar para onde havia sido chamada.
- Cada chamada de função que você escreve hoje faz a mesma coisa, e toda biblioteca de linguagem deriva daquela fita.
- Esta lição trata de procedimentos e funções: como defini-las, como passar valores para dentro e para fora, e como escrever uma à maneira como o Paper 2 as avalia.
Procedures and functions
- Structured programming 结构化编程 builds a program from small named subroutines 子程序, each with one job.
- A procedure 过程 is a named block that does an action and returns nothing:
PROCEDURE Greet(Name : STRING) … ENDPROCEDURE, run withCALL Greet("Ada"). - A function 函数 returns a value that becomes part of an expression:
FUNCTION Square(X : INTEGER) RETURNS INTEGER … RETURN X * X … ENDFUNCTION, used asResult ← Square(5) + 1.
A procedure does something; a function hands back a value
Procedimentos e funções
- Structured programming 结构化编程 constrói um programa a partir de pequenos subroutines 子程序 nomeados, cada um com um trabalho.
- Um procedure 过程 é um bloco nomeado que executa uma ação e retorna nada:
PROCEDURE Greet(Name : STRING) … ENDPROCEDURE, executado comCALL Greet("Ada"). - Um function 函数 retorna um valor que se torna parte de uma expressão:
FUNCTION Square(X : INTEGER) RETURNS INTEGER … RETURN X * X … ENDFUNCTION, usado comoResult ← Square(5) + 1.

Uma procedure faz algo; uma function devolve um valor
The call stack: push on call, pop on return · A pilha de chamadas: empilha na chamada, desempilha no retorno
Calling a subroutine pushes a new frame on top; returning pops it and hands a value back to the caller. The call that is running is always the frame on top. · Chamar uma subrotina empilha um novo quadro no topo; retornar o desempilha e devolve um valor ao chamador. A chamada que está executando é sempre o quadro no topo.
The key difference between a procedure and a function is that a function: · A diferença chave entre um procedimento e uma função é que uma função:
A function returns a value (used in an expression); a procedure performs an action and returns nothing. · Uma função retorna um valor (usado em uma expressão); um procedimento realiza uma ação e não retorna nada.
A function Square(x) returns · decrescentes x * x. What does the call Square(5) return? · Uma função Square(x) retorna x * x. O que a chamada Square(5) retorna?
5 × 5 = 25 — the value the function hands back to its caller (the frame popped off the call stack). · 5 × 5 = 25 — o valor que a função devolve ao seu chamador (o quadro removido da pilha de chamadas).
Where each is appropriate
- A procedure where the same group of steps is needed at several points: validate an input, print a menu, swap two values. The steps are written once and called by name.
- A function where a single value must be calculated and then used in an expression: a total, a
TRUE/FALSEresult, the larger of two numbers. The return value replaces the call. - Use a subroutine when logic appears in more than one place, when a block has a clear named purpose, when the program is complex enough to need decomposition 分解, or when you want to test one piece on its own.
Onde cada um é apropriado
- Um procedure onde o mesmo grupo de etapas é necessário em vários pontos: validar uma entrada, imprimir um menu, trocar dois valores. As etapas são escritas uma vez e chamadas por nome.
- Um function onde um único valor deve ser calculado e depois usado em uma expressão: um total, um resultado
TRUE/FALSE, o maior de dois números. O valor de retorno substitui a chamada. - Use uma subroutine quando a lógica aparecer em mais de um lugar, quando um bloco tiver um propósito nomeado claro, quando o programa for complexo o suficiente para precisar de decomposition 分解, ou quando você quiser testar uma peça sozinha.
A good reason to write a subroutine is that: · Uma boa razão para escrever uma subrotina é que:
Subroutines remove duplication, give a named purpose, and can be tested in isolation. · Subrotinas removem duplicação, dão um propósito nomeado e podem ser testadas isoladamente.
Parameters, arguments and the interface
- Parameters 参数 are the variables a subroutine declares to receive values; the values the caller supplies are the arguments 实参.
- The header is the first line:
PROCEDURE Name(Param : TYPE)orFUNCTION Name(Param : TYPE) RETURNS TYPE. The interface, or signature 签名, is the name, the parameters in order with their types, and the return type: everything a caller must know. - The return value is what a function passes back with
RETURN.
Parâmetros, argumentos e a interface
- Parameters 参数 são as variáveis que uma subroutine declara para receber valores; os valores que o caller fornece são os arguments 实参.
- O header é a primeira linha:
PROCEDURE Name(Param : TYPE)ouFUNCTION Name(Param : TYPE) RETURNS TYPE. O interface, ou signature 签名, é o nome, os parâmetros em ordem com seus tipos, e o tipo de retorno: tudo o que um caller precisa saber. - O return value é o que uma function passa de volta com
RETURN.
Match each term to what it means. · Combine cada termo com o que ele significa.
Function vs procedure = returns a value or not; by value vs by reference = copy or original. · Função vs procedimento = retorna valor ou não; por valor vs por referência = cópia ou original.
Worked example: describe each term in a header
FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN.FUNCTION: a subroutine that returns a value.Pass2: the identifier used to call it.Count: the parameter, the identifier that receives the argument passed in.INTEGER: the data type of that parameter.RETURNS BOOLEAN: the data type of the value the function returns. Five parts, one mark each.
Exemplo resolvido: descrever cada termo em um header
FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN.FUNCTION: uma subroutine que retorna um valor.Pass2: o identificador usado para chamá-la.Count: o parâmetro, o identificador que recebe o argumento passado.INTEGER: o tipo de dados desse parâmetro.RETURNS BOOLEAN: o tipo de dados do valor que a function retorna. Cinco partes, um ponto cada.
In FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN, the identifier Count is the ____. · Em FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN, o identificador Count é o ____.
The parameter receives the argument the caller passes in and is used inside the function like a local variable. · O parâmetro recebe o argumento que o chamador passa e é usado dentro da função como uma variável local.
Pass by value and pass by reference
- Pass by value 传值: the routine receives a copy, so changes inside it do not reach the caller. Use it for inputs the routine only reads.
- Pass by reference 传引用: the routine receives a reference to the caller's own variable, so changes do reach the caller. Use it when the routine must update the argument, as in
Swap. - Cambridge writes the mode in the header,
BYVALorBYREF, before each parameter. If neither is written,BYVALis assumed.
A copy, or a link to the caller's variable
Pass by value e pass by reference
- Pass by value 传值: a routine recebe uma cópia, então mudanças dentro dela não chegam ao caller. Use para entradas que a routine apenas lê.
- Pass by reference 传引用: a routine recebe uma referência à própria variável do caller, então mudanças chegam ao caller. Use quando a routine precisa atualizar o argumento, como em
Swap. - Cambridge escreve o modo no header,
BYVALouBYREF, antes de cada parâmetro. Se nenhum for escrito,BYVALé assumido.

Uma cópia, ou um link para a variável do caller
Worked example: what is output?
Xis a reference toA, soAbecomes 8.Yis a copy ofB, so doublingYleavesBat 3.- The output is
8, 3. Had the header saidBYVAL X,Awould still be 5.
Exemplo resolvido: qual é a saída?
PROCEDURE Adjust(BYREF X : INTEGER, BYVAL Y : INTEGER)
X <- X + Y
Y <- Y * 2
ENDPROCEDURE
A <- 5
B <- 3
CALL Adjust(A, B)
OUTPUT A, B
Xé uma referência aA, entãoAse torna 8.Yé uma cópia deB, então dobrarYdeixaBem 3.- A saída é
8, 3. Se o header dissesseBYVAL X,Aainda seria 5.
In the worked example, what is the value of A after CALL Adjust(A, B)? · No exemplo resolvido, qual é o valor de A após CALL Adjust(A, B)?
X is passed BYREF, so X ← X + Y adds 3 to the caller's A: 5 + 3 = 8. B stays 3 because Y was a copy. · X é passado BYREF, então X ← X + Y adiciona 3 ao A do chamador: 5 + 3 = 8. B permanece 3 porque Y foi uma cópia.
Local and global variables
- A local variable 局部变量 is declared inside a subroutine and exists only while it runs; a global variable 全局变量 is declared outside and is visible everywhere. The region where a name is visible is its scope 作用域.
- Locals are preferred: the same identifier can be reused elsewhere without a clash, the value cannot be changed accidentally by other parts of the program, the memory is released on return, and the subroutine is self-contained.
- A local is created new on every call, so it cannot carry a value between calls. A routine that builds up a string over repeated calls needs that string to be global, or passed
BYREF.
A global is visible everywhere; a local lives only inside its own subroutine
Variáveis locais e globais
- Uma local variable 局部变量 é declarada dentro de uma subroutine e existe apenas enquanto ela roda; uma global variable 全局variable é declarada fora e é visível em todos os lugares. A região onde um nome é visível é seu scope 作用域.
- Locais são preferidos: o mesmo identificador pode ser reutilizado em outro lugar sem colisão, o valor não pode ser alterado acidentalmente por outras partes do programa, a memória é liberada no retorno, e a subroutine é autocontida.
- Um local é criado novo em cada chamada, então não pode carregar um valor entre chamadas. Uma routine que constrói uma string através de chamadas repetidas precisa que essa string seja global, ou passada
BYREF.

Um global é visível em todos os lugares; um local vive apenas dentro de sua própria subroutine
A local variable exists only inside the subroutine where it is declared, while a global variable is visible everywhere in the program. · Uma variável local existe apenas dentro da subrotina onde é declarada, enquanto uma variável global é visível em toda parte no programa.
Keeping variables local limits their scope, avoids name clashes, and makes a subroutine testable on its own — globals are best avoided. · Manter variáveis locais limita seu escopo, evita colisões de nomes e torna uma subrotina testável sozinha — globais devem ser evitadas.
Which are benefits of using local variables? Select all · todos that apply. · Quais são benefícios de usar variáveis locais? Selecione todas as opções.
A local is created fresh on every call, so it cannot keep a value between calls. That is the one job a global, or a BYREF parameter, does instead. · Uma local é criada fresca em cada chamada, então não pode manter um valor entre chamadas. Essa é a única função que uma global, ou um parâmetro BYREF, faz em vez disso.
Turning a procedure into a function
- Change
PROCEDUREtoFUNCTIONand addRETURNS <type>to the header. - Replace the
OUTPUT, or theBYREFparameter that carried the result out, with aRETURNstatement. - Change every call so the returned value is used:
Result ← Unpack(Text)instead ofCALL Unpack(Text, Result).
Transformando uma procedure em uma function
- Mude
PROCEDUREparaFUNCTIONe adicioneRETURNS <type>ao header. - Substitua o
OUTPUT, ou oBYREFparâmetro que carregava o resultado para fora, por uma instruçãoRETURN. - Mude todas as chamadas para que o valor retornado seja usado:
Result ← Unpack(Text)em vez deCALL Unpack(Text, Result).
To convert a procedure into a function you change the header to FUNCTION with RETURNS, replace the OUTPUT with RETURN, and change the calls to use the returned value. · Para converter um procedimento em uma função, você altera o cabeçalho para FUNCTION com RETURNS, substitui o OUTPUT por RETURN, e altera as chamadas para usar o valor retornado.
Three changes, three marks: the header, the RETURN, and the calls. · Três mudanças, três marks: o cabeçalho, o RETURN, e as chamadas.
Worked example: writing a module for Paper 2
- A global array
Score : ARRAY[1:50] OF INTEGERholds test scores. Write a functionCountAbove(Limit : INTEGER)that returns how many scores are greater thanLimit.
- The scheme awards a mark per feature: the header with parameter and return type, the local declarations, the counter initialised before the loop, the loop over every element, the condition with the right comparison, the update inside it, the constructs closed, and one
RETURNafter the loop. - An unfinished module still scores for every correct part, so write all of them.
Each part of a module answer carries its own mark
Exemplo resolvido: escrever um módulo para o Paper 2
- Um array global
Score : ARRAY[1:50] OF INTEGERcontém notas de prova. Escreva uma functionCountAbove(Limit : INTEGER)que retorna quantas notas são maiores queLimit.
FUNCTION CountAbove(BYVAL Limit : INTEGER) RETURNS INTEGER
DECLARE Index, Count : INTEGER
Count <- 0
FOR Index <- 1 TO 50
IF Score[Index] > Limit THEN
Count <- Count + 1
ENDIF
NEXT Index
RETURN Count
ENDFUNCTION
- O scheme atribui um ponto por característica: o header com parâmetro e tipo de retorno, as declarações locais, o contador inicializado antes do laço, o laço sobre cada elemento, a condição com a comparação certa, a atualização dentro dela, os constructs fechados, e um
RETURNapós o laço. - Um módulo inacabado ainda pontua por cada parte correta, então escreva todas elas.

Cada parte de uma resposta de módulo carrega seu próprio ponto
Put the parts of a Paper 2 module answer in the order they are written. · Coloque as partes de uma resposta de módulo Paper 2 na ordem em que são escritas.
Header, declare, loop, condition, update, return. Each part is a mark, even if another part is wrong. · Cabeçalho, declare, laço, condição, atualização, retorno. Cada parte é uma mark, mesmo se outra parte estiver errada.
Marks that slip away
- A routine that must change the caller's variable needs
BYREFin its header; without itBYVALis assumed and the change is lost. - A function has one
RETURN, after the loop, andENDFUNCTION. ARETURNinside the loop ends it on the first element. DECLAREevery local, and initialise a counter or total to 0 before the loop.- "Efficient pseudocode" means moving work that does not change out of the loop, stopping a search at the first match, and not repeating a call whose result could be stored.
Marcas que escapam
- Uma routine que deve alterar a variável do caller precisa de
BYREFem seu header; sem issoBYVALé assumido e a alteração é perdida. - Uma function tem um
RETURN, após o laço, eENDFUNCTION. UmRETURNdentro do laço o encerra no primeiro elemento. DECLAREtodo local, e inicie um contador ou total para 0 antes do laço.- "Efficient pseudocode" significa mover trabalho que não muda para fora do laço, parar uma busca no primeiro match, e não repetir uma chamada cujo resultado possa ser armazenado.
To make a loop more efficient, a value that does not change with the loop counter should be: · Para tornar um laço mais eficiente, um valor que não muda com o contador do laço deve ser:
Hoisting a loop invariant out avoids recomputing the same value on every iteration. · Elevação de um invariante de laço evita recalcular o mesmo valor a cada iteração.
You've got it
- a procedure does an action and is
CALLed; a function returns a value used in an expression - the header names the routine, its parameters with types and the return type; arguments are the values passed in
- BYVAL passes a copy (the default); BYREF lets the routine change the caller's variable
- prefer local variables; a local is new on every call, a global keeps its value
- a Paper 2 module: header, declarations, initialisation, loop, condition, update, closed constructs, one
RETURN
Entendeu?
- uma procedure executa uma ação e é
CALLed; uma function retorna um valor usado em uma expressão - o header nomeia a routine, seus parameters com tipos e o tipo de retorno; arguments são os valores passados
- BYVAL passa uma cópia (o padrão); BYREF permite que a routine altere a variável do caller
- prefira variáveis local; um local é novo em cada chamada, um global mantém seu valor
- um módulo Paper 2: header, declarações, inicialização, laço, condição, atualização, constructs fechados, um
RETURN