Global variables

Hello,
I have a problem with declaring a variable which can be used in functions.
Let's say I want to do something like this:

1
2
3
4
5
6
7
8
9
10
int G_NUMBER; //a global variable (being initialized with 0)
int main()
{
int number;
cin >> number;

G_NUMBER = number; // ERROR - how to change G_NUMBER value? 

return 0;
}

I want to use the same value of G_NUMBER as a CONST value in a lot of functions, but I can't use #DEFINE for this because this value is from input.
How can I do it so other functions will see this value which was from input?
Thanks!
Last edited on
Your compiler should not be having a problem with line 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

int G_NUMBER { };

void aFunc();

int main()
{
   std::cout << "In main: " << G_NUMBER << "\n\n";

   aFunc();

   std::cout << "Enter a number for the global: ";
   int number { };
   std::cin >> number;
   std::cout << '\n';

   G_NUMBER = number; // no error

   aFunc();

   std::cout << "In main: " << G_NUMBER << '\n';
}

void aFunc()
{
   std::cout << "In aFunc: " << G_NUMBER << "\n\n";
}

In main: 0

In aFunc: 0

Enter a number for the global: 12

In aFunc: 12

In main: 12


Using globals has a trap, the value(s) can be change anywhere in your code. That makes tracking "wrong" values hard to do.

Passing local variables by pointer or reference is preferred over using globals.
Last edited on
Topic archived. No new replies allowed.