9

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

Thanks Jack

1 Answer 1

31

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 -- which is why default arguments are specified in the header file rather than in the implementation file.
+1 I never thought deeply about this, but your answer makes perfect sense! It also simplifies things considerably; when I started using C++, I wondered how a virtual function could be overridden when it has default parameter values. I was thinking that the default values modified the signature somehow or generated more functions, but just dealing with it at the call site (not doing anything to the function itself) makes the most sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.