Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default argument value

Tags:

c++

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

Thanks Jack

like image 691
user382499 Avatar asked Jul 03 '10 02:07

user382499


1 Answers

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.

like image 166
Greg Hewgill Avatar answered Sep 21 '22 13:09

Greg Hewgill