Beginner's Guide
    First Steps
    Input & Output
    Basic Custom Types
    Diagnostics
    Standard Library
    Code Organization
    Powerful Custom Types
    Generic Programming
    Memory Management
    Software Design Basics

    Function Call MechanicsFunction CallsFunction Calls

    Reminder: Memory Organisation Memory Organisation Memory

    How Function Calls Work How Calls Work How?

    No References To Locals No Ref To Locals Return Refs?

    Common Compiler Optimizations Compiler Optimizations Optimizations

    Modern C++ compilers perform several optimizations (especially at higher optimization levels -O2 and -O3) that make function calls much faster.

    Applies to statements like return Type{}; or return Type{argument,};.

    No extra placeholder for the return value is allocated, no copy takes place. Instead, the external object res is directly constructed at the call site.

    This optimization is mandatory, i.e., guaranteed to be performed as of C++17.

    Calls to small/short functions are replaced with the code of the function.

    int square(int x) { 
      return x * x; 
    }
    
    int y = 0; std::cin >> y; std::cout << square(y);
    int y = 0;
    std::cin >> y;
    std::cout << (y*y);

    Inlining can only happen, if the compiler "sees" not only the function declaration but also its full definition, which is not necessarily the case, if we compile different parts of a program separately (more in chapter Separate Compilation).

    This is one source of C++'s performance advantages. Inlining is a lot harder or sometimes impossible in many other languages like Java, C#, etc. with always-on polymorphism which means that all/most function/method calls can only be resolved at runtime.