What is the primary use of a global variable in C++?
2024
What is the primary use of a global variable in C++?
Answer: C. To allow data to be accessed from multiple functions in a program — ConceptIn C++, the region of code where a name is visible is called its scope. A variable declared outside every function and class - at file (namespace)…
- A.
To store values that can be accessed only inside a loop
- B.
To create variables that exist only during function execution
- C.
To allow data to be accessed from multiple functions in a program
- D.
To permanently store data inside a file
- E.
To declare variables that cannot be modified
Attempted by 132 students.
Show answer & explanation
Correct answer: C
Concept
In C++, the region of code where a name is visible is called its scope. A variable declared outside every function and class - at file (namespace) level - has global scope: it is created when the program starts, lives for the entire run of the program, and its name is visible to every function defined after it in the same translation unit. This is what distinguishes it from a local variable, whose name is visible only inside the block that declares it.
Application
The question asks for the primary use of a global variable. Because a global variable lives at file level rather than inside any one function, the same single variable can be read and written by many different functions without being passed around as a parameter or returned as a value. So its defining purpose is exactly that: to let data be shared and accessed across multiple functions in the program. That is the option that states data can be accessed from multiple functions.
Why the other choices are wrong
Being usable only inside a loop describes a variable whose scope is limited to that loop block - the opposite of program-wide visibility.
Existing only during a function's execution describes a local (automatic) variable, which is created on each call and destroyed when the function returns; that is local scope, not global.
Permanently storing data inside a file describes file I/O or persistence; a global variable lives only in memory and disappears when the program ends.
Declaring a value that cannot be modified describes a const variable; constness is about whether a value can change, which is independent of whether the variable is global or local.
Cross-check
Scope (where a name is visible) and lifetime (how long the object exists) together explain the answer: a global has the widest scope and the longest lifetime, which is precisely why it is the tool for sharing data among several functions. The other four describe loop scope, local lifetime, file persistence, and immutability respectively - none of which is what makes a variable global.