Information

Author(s) Nicolas Rybowski, Mathieu Xhonneux
Deadline Keine Frist
Abgabenlimit No limitation
Category tags s3, category_pointer, level1

Tags

Einloggen

[S3] Global and local variables

In a C program, variables are stored in different regions in memory, depending on where the variables have been initialized. Each memory region has different properties about how the variables can be accessed, modified, ... This exercise will show you how global variables and variables on the stack are managed.

int result;

void sum1(int a1, int b1) {
    a1 = a1 + b1;
}

void main(int argc, char **argv) {
    int a1 = 5, b1 = 6;

    sum1(a1, b1);
    printf("sum1: %d\n", a1);

    int a2 = 3, b2 = 7;
    sum2(a2, b2);
    printf("sum2: %d\n", result);

    int a3 = 1, b3 = 8;
    int r;
    sum3(&a3, &b3, &r);
    printf("sum3: %d\n", r);
}

Question 1: On the stack

The variables which are declared inside functions are stored on the program's stack. These variables are only accessible by the function in which they were declared.

Moreover, passing arguments to functions, and returning values from a function, also use the stack, and use the mechanism of passing by value. Once a variable is passed by value, a copy of its value is placed on the stack.

Consider the main function here above. What number would the first call to printf print ?

Question 2: Global variables

Write the body of the function sum2 which stores in the global variable result the sum of its parameters. Why does it work with a global variable ?

void sum2(int a, int b) {
Question 3: Passing by reference

You are now asked to return the result of the sum, neither by using the return keyword, nor by using a global variables.

/*
 * @post stores the sum of the values pointed by a and b in the memory pointed by r
 */
void sum3 (int *a, int *b, int *r) {