Global Variables

It is possible to have variables that are not in any specific function. Such a variable is called a global variable and can be declared at the top of the module's .cpp file.

Because a global variable is not “in” a particular function, it is visible to all functions. This means that any function can get or change its value.

This increases the dependence (coupling) between any functions that use the global variable, which makes maintenance more difficult. For this reason, you should avoid the use of global variables, using arguments and return values instead.

One other issue with global variables arises when local and global variables have the same name. In these instances, the local variable takes priority over the global variable, ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.