Skip to main content
Logo image

Dive Into Systems: Exercises

Section 2.1 Parts of Program Memory and Scope

Exercise 2.1.1. Global Variables vs. Parameters.

    What is the primary difference between global variables and function parameters? Select all that are true.
  • Global variables can be accessed and modified by any function within the program, while parameters are limited to the specific function they are declared in.
  • Global variables are stored in the heap memory, while parameters are stored in the stack memory.
  • Global variables have a longer lifespan and persist throughout the entire execution of the program, whereas parameters are temporary and remain in scope only during the execution of their respective function.
  • Global variables can only hold integer values, whereas parameters can store any data type.

Exercise 2.1.2. Code Tracing: Global Variables.

What is the output of the following program?
#include <stdio.h>

int gval;

int f6(void) {
    return (2 * gval - 6);
}

int main(void){
    gval = 17;
    gval = f6();
    printf("%d\n", gval);

    return 0;
}

Exercise 2.1.3. Variable Scope.

    What would happen when we attempt to run the following code snippet?
    #include <stdio.h>
    
    int global_variable = 10; 
    
    void my_function(int local_parameter) {
        int local_var; 
    
        local_var = 20;
    
        printf("Global variable: %d\n", global_variable);
        printf("Local parameter: %d\n", local_parameter);
        printf("Local variable: %d\n", local_var);
    }
    
    int main(void) {
        int main_var;
    
        main_var = 30; 
    
        my_function(40);
    
        printf("Global variable: %d\n", global_variable);
        printf("Local parameter: %d\n", local_parameter); 
        printf("Local variable: %d\n", local_var); 
        printf("Main variable: %d\n", main_var);
    
        return 0;
    }
    
  • It will print out four different print statements.
  • It will print out seven different print statements.
  • It will not compile.
  • There are compilation errors on the second and third printf statements in main. After commenting them out, this is what prints when the program is executed:
    Global variable: 10
    Local parameter: 40
    Local variable: 20
    Global variable: 10
    Main variable: 30
    
  • It will compile, but results in a runtime error.