UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

3.4.  Exercises

  1. Consider the following variable declarations (the code not shown does not modify the value of any of the variables).

    File 1 File 2 File 3
    int n1 = 1;
    static int n2 = 2;
    int n3 = 3;
    
    void function1() 
    {
        int n1 = 10;
        ....
    }
    void function2() 
    {
        ....
    }
    extern int n1;
    static int n2 = 20;
    
    void function3() 
    {
       static int n1 = 100;
     
        n1++;
        ....
    }
    void function4() 
    {
        ....
    }
    int n4 = 4;
    static int n2 = 200;
    
    void function5() 
    {
        static int n2 = 2000;
    
        n2++;
        ....
    }
    void function6() 
    {
        ....
    }

    Answer the following questions.

    Question Answer
    What is the value of n1 in function1?
    What is the value of n1 in function2?
    What scope of validity does variable n4 have?
    What happens if n4 is accessed from function1 or function2?
    What value does variable n1 have at the end of function function3 the first time it is invoked? And the second?
    What value does variable n1 have at the end of function function4 the first time it is invoked? And the second?
    How many instances of variable shadowing are in this program?
    What is the value of n2 the second time function6 is executed?
    What value does variable n2 have at the end of function function5 the first time it is invoked? And the second?
  2. A programmer with a not-so-polished programming style has defined the following data structure in an application:

    struct the_most_important_data_structure_in_the_application 
    {
        int a;
        int b;
    };

    You have to declare numerous variables of this type in several locations in the code. You cannot modify the code written by this programmer. What do you propose to facilitate these declarations?

  3. In a program with a large number o files, the first and last name of the author (which is not the same for all files) needs to be stored in each file. The name of this variable needs to be the same in all files. How would you declare these variables in each file? Of which type?

  4. Can you think of a functionality in a program requiring a static variable in a function?

  5. How would you store the number of times a function is invoked but without defining any global variable?