Categories
Development

Why in this code, the static int doesn’t change or give a compilation error?

I have a code here. It was a puzzle to solve. However I couldn’t understand the part about the header_var which is a static int. Why is it possible to change the value of header_var from q1_main.cpp and that it doesn’t change its value in q1_helper.cpp.Also why don’t I receive any warning or compilation error?

Below are the codes:

q1_main.cpp:

#include <iostream>
#include "q1_header.h"
using namespace std;
void func_1(int param_1);
void func_2(int& param_2);
void func_3(int* param_3);
void func_4();
int global_var = -1;
int main() {
    int local_var_1 = -1;
    int local_var_2 = -1;
    int *local_var_3 = new int;
    *local_var_3 = -1;
    //The first line of the output
    func_1(local_var_1);
    func_2(local_var_2);
    func_3(local_var_3);
    cout << local_var_1 << " " <<
        local_var_2 << " " <<
        *local_var_3 << endl;
    //The second line of the output
    func_1(global_var);
    cout << global_var << endl;
    //The third line of the output
    header_var = 5;
    func_4();
    cout << global_var << " " <<
        header_var << endl;
    //The fourth line of the output
    loop(i, 2) {
        static int static_var = 0;
        cout << static_var++ << " ";
    }
    cout << endl;
    return 0;
}

q1_helper.cpp:

#include <iostream>
#include "q1_header.h"
extern int global_var;
void func_1(int param_1) {
    param_1 = 100 / ADD(2,3);
}
void func_2(int& param_2) {
    param_2 = 100 / MUL(50, 2);
}
void func_3(int* param_3) {
    *param_3 = 200 / (ADD(2,8) * MUL(10,2));
}
void func_4() {
    global_var = 100 / ADD(2,3);
    header_var = 10;
}

q1_header.h:

#ifndef Q1_HEADER_H
#define Q1_HEADER_H
#define ADD(x,y) x + y
#define MUL(x,y) x * y
#define loop(x,n) for(int x=1; x<=n; ++x)
static int header_var = -1;
#endif

Leave a Reply

Your email address will not be published. Required fields are marked *