Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The scope of the variable


May 11, 2021 C++


Table of contents


The scope of the variable

A scope is an area of a program that generally has three places to declare variables:

  • A variable declared inside a function or block of code, called a local variable.
  • A variable declared in the definition of a function argument, called a formal argument.
  • A variable declared outside all functions, called a global variable.

We'll learn what functions and parameters are in a later section. In this chapter, let's start by explaining that declarations are local and global.

The local variable

A variable declared inside a function or block of code, called a local variable. T hey 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 ()
{
  // 局部变量声明
  int a, b;
  int c;
 
  // 实际初始化
  a = 10;
  b = 20;
  c = a + b;
 
  cout << c;     return 0; 
} 

Global variable

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

Global variables can be accessed by any function. T hat is, once declared, global variables are available throughout the program. 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 a program, the names of local and global variables can be the same, but within a function, the value of a local variable overrides the value of the global variable. Here's 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 department variable is defined, it is not initialized by the system and you must initialize it yourself. When you define a global variable, the system automatically initializes to the following values:

type of data Initialization default value
int 0
char '\0'
float 0
double 0
pointer NULL

It is a good programming habit to initialize variables correctly, otherwise sometimes programs can produce unexpected results.