« Macros and Global variables

Use cases of macros and global variables

Macros

1#include <iostream>

These are preprocessor directive. When we start to compile this code will copy all the iostream code here first, meaning these preprocessor directive will work before code gets actually compiled.

1#define PI 3.14

Its going to work before code gets actually compiled. Its going to find all the PI all over the code and replace it with 3.14. Compiler will see 3.14 at all the places of PI.

1int r;
2cin >> r;
3double pi = 3.14;
4cout << pi * r * r << endl;
5
6pi = pi+1;
  • First problem here is if someone changes pi at someplace then, whole code will break.
  • Second problem is the extra storage we are using for pi.
  • Each time we need to access variable pi so its a extra work we need to perform each time.

Global variable

1int a;
  • This is global variable. This is a bad practice. Its better to share references and should be handled properly.
  • Scope of the global variable is whole program. It will be de-allocated after the program ends.
  • Its too much flexibility that anyone can change the variable and its accessible to all the functions.
  • It will be hard to track if somewhere value is changed by mistake.

Final code

1#include <iostream> //preprocessor directive.
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13#define PI 3.14 // macro
14
15int a;
16// global variable
17
18void g()
19{
20 a++;
21 cout << a << endl;
22}
23
24void f()
25{
26 cout << a << endl;
27 a++;
28 g();
29}
30int main()
31{
32 int r;
33 cin >> r;
34 // double pi = 3.14;
35 cout << PI * r * r << endl;
36
37 // pi = pi + 1;
38
39 a = 10;
40 f();
41 cout << a << endl;
42 return 0;
43}