Latest web development tutorials

C ++ variable scope

Scope is a regional program, in general, there are three places you can declare variables:

  • Function or variable declared inside a block of code, called local variables.
  • Variables declared in the definition of the function parameters, called formal parameters.
  • All variables declared outside a function, called global variables.

We will learn in later chapters what is the function and parameters. In this chapter we first explain to declare a local and global variables.

Local variables

Function or variable declared inside a block of code, called local variables. They can only be used inside a function or block of code inside the statement. The following example uses local variables:

#include <iostream>
using namespace std;
 
int main ()
{
  // 局部变量声明
  int a, b;
  int c;
 
  // 实际初始化
  a = 10;
  b = 20;
  c = a + b;
 
  cout << c;
 
  return 0;
}

Global Variables

In all the variables defined outside the function (usually the head of the program), known as global variables. The value of a global variable over the entire life cycle of the program are valid.

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

#include <iostream>
using namespace std;
 
// 全局变量声明
int g;
 
int main ()
{
  // 局部变量声明
  int a, b;
 
  // 实际初始化
  a = 10;
  b = 20;
  g = a + b;
 
  cout << g;
 
  return 0;
}

In the program, local variables and global variables can be the same, but inside a function, local variables will override the value of a global variable. Here is an example:

#include <iostream>
using namespace std;
 
// 全局变量声明
int g = 20;
 
int main ()
{
  // 局部变量声明
  int g = 10;
 
  cout << g;
 
  return 0;
}

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

10

Initialize local and global variables

When a local variable is defined, the system does not initialize, you must initialize it yourself. When you define global variables are automatically initialized to the following values:

数据类型初始化默认值
int 0
char '\0'
float 0
double 0
pointer NULL

Properly initialized variable is a good programming practice, otherwise the program may sometimes produce unexpected results.