OneBite.Dev - Coding blog in a bite size

declare a global variable in C++

Code snippet on how to declare a global variable in C++

  int global_var;

This code declares a global variable in C++. The keyword “int” declares the data type of the variable, in this case, an integer. Then, the variable is named as “global_var”. Since it has no modifiers (e.g. static, const) or initialization, the default value is null or 0, in this case.

The “global_var” can be accessed from any part of the code and any function, since it is declared globally. The scope of the variable is set to the file in which it is declared, therefore, any reference to the “global_var” outside the file will result in a compiler error.

c-plus-plus