-3

In C++ language is there any disadvantage to declare a variable global?

void foo()
{
  int a;
  a=10;
}

int a;
void foo()
{
  a=10;
}

Any differences between them?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
noDispName
  • 53
  • 1
  • 1
  • 6

5 Answers5

19

Why Global Variables Should Be Avoided When Unnecessary

  • Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use.
  • No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten. (In other words, get/set accessors are generally preferable over direct data access, and this is even more so for global data.) By extension, the lack of access control greatly hinders achieving security in situations where you may wish to run untrusted code (such as working with 3rd party plugins).
  • Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.
  • Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often neglected). When dynamically linking modules with globals, the composed system might not be thread-safe even if the two independent modules tested in dozens of different contexts were safe.
  • Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local (by misspelling or forgetting to declare the local) or vice versa. Also, if you ever have to link together modules that have the same global variable names, if you are lucky, you will get linking errors. If you are unlucky, the linker will simply treat all uses of the same name as the same object.
  • Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.
  • Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort (e.g. reading and writing files or databases) that aren't explicitly provided to that source is difficult to test for the same reason. For communicating systems, the ability to test system invariants may require running more than one 'copy' of a system simultaneously, which is greatly hindered by any use of shared services - including global memory - that are not provided for sharing as part of the test.
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Pavan
  • 507
  • 1
  • 3
  • 15
1

Global variable's memory is not automatically freed. While scope variable's memory is freed as soon as the completion of block.

void foo()
{
  int a;
  a=10;
}

This int a will be freed after the completion of foo

int a;
void foo()
{
  a=10;
}

This int a will be freed depending upon its scope outside foo()

0

Memory usage. In first case memory will be freed, in second will not. And ofc this is very bad to declare variable with name like ''A'' as global variable. This will be source of great number of errors.

Darthman
  • 457
  • 4
  • 21
  • Will be freed? I don't think C++ have garbage collector. – noDispName Jul 26 '13 at 07:08
  • @kutluhanmetin Variables declared on the stack (non-pointer, local variables) are freed when they go out of scope. In fact, you can't delete them if you tried. – mpen Jul 26 '13 at 07:09
  • There is no need in garbage collector to free memory for simple types like int. If you will use classes as global variables it will not free ofc. – Darthman Jul 26 '13 at 07:10
  • @kutluhanmetin It's not about garbage collection. It's about returning resources to the system. In C++ a global variable will take up memory throughout the lifetime of the process. The local variable would only temporarily take up space on the stack. – Agentlien Jul 26 '13 at 07:10
  • @Darthman, The memory from every variable not `new`ed is freed automatically. It doesn't matter whether it's a fundamental type or not. – chris Jul 26 '13 at 07:22
0

In the first, the variable lives on the stack and is only valid until the function exits, and it is visible only from inside the function. In the second, it is both valid and accessible from outside.

As a general rule, you should always declare a variable as local as possible, so only use global variables when it is really necessary.

There is a third variant. If you do this:

void foo()
{
static int a;
a=10;
}

Then your variable remains valid after the function exits, but it is only visible from inside (although you can give out pointers or references if you want). This is the recommended usage if you need a variable that needs to retain its value between function calls but is only used from within the function.

petersohn
  • 11,292
  • 13
  • 61
  • 98
0

This has been discussed before on StackOverflow. See for example this:

https://stackoverflow.com/a/485020/980195

The main disadvantages of putting variables in global scope is precisely that they become globally accessible. Any other piece of code could decide to read or write to them. Whereas with a local variable, you only need to look to the local scope in order to know everything which is going to be able to change or even access the value.

Apart from that, putting it in the global namespace means it can give rise to name clashes, ambiguity or even users accidentally referring to the wrong variable through a simple typo. This is especially bad if you call your variable something as simple as in your case.

There are more reasons as well, for example look at the answer @naren provided.

Community
  • 1
  • 1
Agentlien
  • 4,996
  • 1
  • 16
  • 27