9

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

Thanks Jack

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
user382499
  • 587
  • 3
  • 8
  • 11

1 Answers1

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 9
    +1 -- which is why default arguments are specified in the header file rather than in the implementation file. – Billy ONeal Jul 03 '10 at 02:44
  • +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. – stinky472 Jul 03 '10 at 03:47