What is the declaration method for global variables in C++?

In C++, global variables can be declared at any position outside functions. The declaration of global variables can be divided into two steps.

  1. Declare the variable outside the function and specify its type and name. For example:
int globalVariable;
  1. external
extern int globalVariable;

It’s important to note that the definition and declaration of global variables can be done separately. Defining a global variable means allocating memory space for it, while declaring just informs the compiler of its existence. When declaring a global variable, you can define it in another file and then reference it using the extern keyword.

Leave a Reply 0

Your email address will not be published. Required fields are marked *