Understanding Function Calls in C++

Jul 4, 2024

Lecture Notes: Understanding Function Calls in C++

Introduction

  • Discussing functions in C++.
  • Previously covered topics:
    • Basics of functions
    • Call by value vs. call by reference
    • Function overloading
    • Passing arrays to functions
    • Coding exercises

Focus of This Lecture

  • How function call works: Internal mechanism
    • Transition of control from main function to the called function.
    • Understanding memory segments and their role in function calls.

Memory Layout of a Program

  • Segments in memory: Code, static/global, stack, heap.
    • Code Area: Contains the actual program code.
    • Static/Global Area: Memory for static or global variables.
    • Stack: Used during function calls; works on LIFO (Last In First Out) principle.
    • Heap: Free storage, used for dynamic memory allocation (not covered in this lecture).

Stack Memory and Function Calls

  • Functions use stack memory for their activation records.
  • Activation Records: Store information about the function e.g., parameters, local variables, temporary variables, return address.
  • Stack Size: Finite; possibility of stack overflow error if too many activation records.

Activation Record Lifecycle

  1. Function Call: Activation record pushed onto the stack.
  2. Function Execution: Control transfers to the called function; execution proceeds with local parameters and variables.
  3. Function Return: Activation record popped from the stack; control returns to the calling function.

Practical Example

  • Example Program: Finding a sum and difference through function calls.

Steps in Execution

  1. Main Function:

    • Entry in the stack for main function created.
    • Local variables initialized (num1, num2, result).
  2. Calling Addition Function:

    • Entry created for addition function.
    • Parameters passed; local variables initialized (a, b, sum).
  3. Calling Subtraction Function from Addition:

    • Entry for subtraction function created.
    • Parameters passed by reference for sum and by value for others.
    • Local variables initialized (x, y, z).
  4. Function Execution: Subtraction:

    • Calculation: x = x - y - z alters the sum due to pass by reference.
    • No return value; control returns to addition function.
  5. Completion of Addition Function:

    • Return sum to main; activation record of addition removed.
    • result in main updated.
  6. Main Function Continues:

    • Print result and terminate.
    • Final activation record for main removed.

Conclusion

  • Insight into internal working of function calls and stack memory utilization.
  • Importance of understanding stack behavior and potential pitfalls like stack overflow.

Next Topics

  • Scope of Variables: Understanding the visibility and lifetime of variables in C++.

  • Recursion in Functions: Basics and applications.

  • End of Lecture -