--- title: Transfer of control - Procedure Call description: Call procedure note. Author - Dzaqwan Amir tags: assignment --- # Transfer of Control There are several types of transfer-of-control - Branch - Skip - Call ## Call procedure - Is the most important innovation in the development of programming language - Two basic instruction in call procedure: - `CALL` - `RETURN` ### How it works in program ![reference link](https://i.imgur.com/aY1OLWh.png) - In this figure, we can see there are 3 separate program parts (code blocks) - Main - Procedure 1 (Proc 1) - Procedure 2 (Proc 2) #### Program flow 1. At some point in main program, Proc 1 is called to be executed (`CALL Proc 1`). The program then jump to Proc 1 2. Then in Proc 1, Proc 2 is called. The program jump to Proc 2 (`CALL Proc 2`) 3. At the end of Proc 2, it hits instruction `RETURN` 4. The program then come back to where it left off when it called Proc 2, which is at address 4600 in Proc 1. 5. Program continues executing instruction in 4601 -- 4649, and met another `CALL Proc 2` instruction. 6. Proc 2 is executed again and return to where it was called, 4650 7. Proc 1 executed until it hit `RETURN` and go back to the main program in address 4100 8. The main program executed sequentially until the end. ### Stack - Because we call a procedure from various places, the processor must somehow **save the return address** so that the return can take place appropriately - It got complicated when there are multiple nested procedure call, where a procedure call another procedure - One way to neatly save the correct return address is by using stack ![reference link](https://i.imgur.com/txW2fbi.png) - Every time a procedure is called, the address where the `CALL` is executed is saved **on top** of a stack. - When a procedure reached `RETURN`, the program take the address on top of the stack to continue where it left off ### Benefit of call procedure - **Economy**: A procedure allows the same piece code to be used many times - **Modularity**: Large programming task can be divided into smaller units