How to modify global variables in C++?
In C++, by default, global variables can be accessed from any part of the program. If you need to modify global variables, you can use the following modifiers:
- The static modifier: global variables that are marked as static can only be accessed within the source file where they are declared. Variables with the same name in other source files will be hidden. This helps prevent global variables from being accidentally modified by other files.
- globalVariable is a global variable with static modifier.
- extern modifier: A global variable declaration with the extern modifier is just a reference to the variable, not an actual definition. It is typically used in conjunction with the actual definition in another source file, allowing the same global variable to be shared across multiple source files.
- Declare a global variable using the extern keyword.
- const modifier: a global variable that is decorated with const indicates that its value cannot be changed during program execution.
- const global variable is designated as 10.
It is important to note that the use of global variables should be cautious, as they may decrease the readability and maintainability of the program. It is recommended to use class member variables and local variables to encapsulate and limit the scope of variables.