A scope is a region of a program that generally has three places where variables can be defined:

  • Variables declared inside a function or a code block are called local variables.

  • Variables declared in the definition of function parameters are called formal parameters.

  • Variables declared outside all functions are called global variables.

We will learn what functions and parameters are in subsequent chapters. In this chapter we begin by explaining what local and global variables are.

A local variable

Variables declared inside a function or a code block are called local variables. They can only be used by statements inside functions or blocks of code. The following example uses local variables:

#include <iostream> using namespace std; Int main () {// local variable declaration int a, b; int c; // a = 10; b = 20; c = a + b; cout << c; return 0; }Copy the code

The global variable

Variables defined outside all functions (usually in the head of a program) are called global variables. The value of a global variable is valid for the entire life of the program.

Global variables can be accessed by any function. That is, global variables, once declared, are available throughout the program. The following example uses global and local variables:

#include <iostream> using namespace std; // global variable declaration int g; Int main () {// local variable declaration int a, b; // a = 10; b = 20; g = a + b; cout << g; return 0; }Copy the code

In a program, the names of local and global variables can be the same, but in a function, the value of the local variable overrides the value of the global variable. Here is an example:

#include <iostream> using namespace std; Int g = 20; Int main () {// local variable declaration int g = 10; cout << g; return 0; }Copy the code

When the above code is compiled and executed, it produces the following results:

10

Initializing local and global variables When local variables are defined, the system does not initialize them. You must initialize them yourself. Global variables are automatically initialized to the following values when they are defined:

Data type initializes the default value

Properly initializing variables is a good programming practice, or programs can sometimes produce unexpected results.

Recently sorted out some suitable for small white people entry learning materials, including e-books, tools, installation packages and so on – point me

Join my official group [free] for a full set of C language mastery materials. (“▔□▔)/ If you are new to C, you can share a full set of C language mastery learning materials to you. If you are learning C++, you can help you to learn the DIRECTION of C++ game development, so that you can think clearly and learn more effectively