This is not the current version of the class.

Data representation 4: Argument passing, sizes, segments

Overview

We discuss C++ value passing and returning, the sizes of objects, and recap some information on segments.

Modifying an argument

def f(arg):
    arg = -1

x = 2
f(x)
print("x is {}".format(x))

Modifying a complex argument

def f(arg):
    arg = [-1]

l = [2]
f(l)
print("l[0] is {}".format(l[0]))

Modifying a complex argument’s value

def f(arg):
    arg[0] = -1

l = [2]
f(l)
print("l[0] is {}".format(l[0]))

C++

C++ modifying an argument

void f(int arg) {
    arg = -1;
}

int main() {
    int x = 2;
    f(x);
    printf("x is %d\n", x);
}

C++ modifying a complex argument

void f(std::vector<int> arg) {
    arg = {-1};
}

int main() {
    std::vector<int> l = {2};
    f(l);
    printf("l[0] is %d\n", l[0]);
}

C++ modifying a complex argument’s value

void f(std::vector<int> arg) {
    arg[0] = -1;
}

int main() {
    std::vector<int> l = {2};
    f(l);
    printf("l[0] is %d\n", l[0]);
}

Call-by-reference

void f(std::vector<int>& arg) {    // `&` means reference
    arg[0] = -1;
}

int main() {
    std::vector<int> l = {2};
    f(l);
    printf("l[0] is %d\n", l[0]);
}

Every declared object has constant size

How does std::vector work?

Array parameters and return values are special

void f(int arg[]) {
    arg[0] = -1;
}

int main() {
    int l[2] = {2, 0};
    f(l);
    printf("l[0] is %d\n", l[0]);
}

Stack segment growth

int f1(int f1arg) {
    hexdump_named_object(f1arg);
    return f1arg;
}

int f2(int f2arg) {
    hexdump_named_object(f2arg);
    return f1(rand()) + f2arg;
}

...

int f5(int f5arg) {
    hexdump_named_object(f5arg);
    return f4(rand()) + f5arg;
}

Recursive call

int f(int x) {
    int r = 0;
    ...
    if (x > 0) {
        r += f(x - 1);
    }
    ...
    return r;
}

int main() {
    f(100);
}

Stack layout vs. struct layout