Explanation of the scope of variables in C++



The scope (scope) is the part of the program in which the name has a specific meaning. In the

C++ language, most scopes are separated by curly brackets.

Note : the same name may refer to different entities in different scopes. The valid area of ​​​​begins with the declaration statement of the name and ends with the end of the scope in which the declaration statement is located.

JAVA;">

int main()

{

  int sum = 0;

  for(intval = 1; val<= 10; ++val)

  sum+= val;

  std::cout << "Sum of 1 to 10 is" << sum << std::endl;

    return 0;

}

As in the above program example, main is defined in all Outside the curly braces, it has a global scope. Once declared, the names in the global scope can be used within the scope of the entire program.

sum has a block scope, which can be used in the main function, but cannot be accessed after the main function.

A suggestion here is to define the object the first time it is used, like:

JAVA;">

int a = 0;

printf(a);

int b = 1;

printf(b);

Note that this is not allowed in the C specification, but C++ supports and recommends it, and for C, different compilers have differences, such as gcc support, the advantage of this is to help make it easier Find the definition of the variable, and more importantly, near where it is first used, we will assign it a more reasonable initial value

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326365928&siteId=291194637