user382499
user382499

Reputation: 607

C++ default argument value

Where does the compiler store default argument values in C++? global heap, stack or data segment?

Thanks Jack

Upvotes: 9

Views: 2325

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993105

They aren't necessarily stored anywhere. In the simplest case, the compiler will compile a function call exactly the same as if the missing arguments were present.

For example,

void f(int a, int b = 5) {
    cout << a << b << endl;
}

f(1);
f(1, 5);

The two calls to f() are likely compiled to exactly the same assembly code. You can check this by asking your compiler to produce an assembly listing for the object code.

My compiler generates:

    movl    $5, 4(%esp)    ; f(1)
    movl    $1, (%esp)
    call    __Z1fii

    movl    $5, 4(%esp)    ; f(1, 5)
    movl    $1, (%esp)
    call    __Z1fii

As you can see, the generated code is identical.

Upvotes: 31

Related Questions