Sobes.tech
Junior — Middle

Millised toimingud toimuvad virnas, kui programmifunktsioon käivitatakse?

sobes.tech AI

Vastus AI-lt

When calling a function in a Go program (and in most languages supporting call stacks), the following happens:

  1. A stack frame is allocated — a memory area for storing local variables, parameters, and the return address.
  2. The return address is saved — so that after the function completes, the program can continue from the correct location.
  3. The function parameters are copied — the argument values are transferred into the new frame.
  4. Local variables are initialized — memory is allocated and, if necessary, initial values are set.

After the function executes, the stack frame is removed, and control returns to the saved address.

Example (simplified):

func add(a, b int) int {
    sum := a + b
    return sum
}

func main() {
    result := add(2, 3)
    fmt.Println(result) // 5
}

When add is called, a frame is created on the stack with parameters a=2, b=3, a local variable sum, and the return address in main.