3.12 Calling Procedures

40 阅读1分钟

1. Exam Points

  • Call given procedures:
    • procName (arg1, arg2, …)
  • Pass arguments to parameters: procName(arg1, arg2, …)
  • Return a value from a procedure: result ← procName(arguments)
  • Note: The code segment after a return statement is unreachable.
  • Predict output/result of executing procedures.

2. Knowledge Points

(1) Understand Procedures

  • A procedure is a named group of programming instructions that may have parameters and return values.
  • Example: develop a procedure and call the procedure
    image.png
  • Input and output in CSP:
    • Input: procedure INPUT()
      • x ← INPUT()
    • Output: procedure DISPLAY(): display a value, followed by a space
      • DISPLAY(”a”)
      • DISPLAY(10)

(2) Develop and Call Procedures

  • Procedures are referred to by different names, such as method or function, depending on the programming language.
  • Syntax:
    image.png
  • Example 1: a procedure with parameters

    • image.png
    • Parameters (形式参数 - count) : input variables of a procedure.
    • Arguments (实际参数 - 5): actual values of the parameters when a procedure is called.
  • Example 2: a procedure with a returned value

    • image.png
    • Note:
      • The RETURN statement may appear at any point inside the procedure and causes an immediate return from the procedure back to the calling statement.
      • If return(a) is executed, then the statements after return(a) in the procedure will not be executed.
      • The code segment after a return statement is unreachable.
    • Purpose of the return statement:
      • Return a value
      • Return the flow of control back

(3) Note

  • A procedure call interrupts the sequential execution of statements, causing the program to execute the statements within the procedure before continuing.
  • Once the last statement in the procedure (or a return statement) has executed, flow of control is returned to the point immediately where the procedure was called.
  • Example: b is displayed only after the last statement in proc2() is executed.
    image.png

3. Exercises