Happy file C++ variable scope

C++ variable scope

A scope is an area of ​​a program. Generally speaking, there are 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 first explain what are local variables and global variables.

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 inside code blocks. The following example uses local variables:

example

#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 top of the program) are called global variables. The value of a global variable is valid throughout the lifetime of the program.

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

example

#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, a local variable and a global variable can have the same name, but within a function, the value of the local variable overrides the value of the global variable. Here is an example:

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 result:


10

Initialize local and global variables

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

type of data Initialize default values
int 0
char '\0'
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables correctly, otherwise the program may produce unexpected results sometimes.

Guess you like

Origin blog.csdn.net/m0_74760716/article/details/131504708