Scope of c++ compound statement

Scope of Compound Statements

In the head of the compound statement, we can not only use external variables, but also directly declare new variables. The scope of such local variables will be the entire compound statement. For some variables that can only be used inside the compound statement, we can use this method to prevent its scope from spreading to the outside, which is beneficial to structured programming.

Scope of Compound Statements

#include<iostream>
using namespace std;
//复合语句的作用域
int main()
{
    
    
//复合语句
if ( int a = 0 )
	cout << "a的值为:" << a <<endl;
else
 	cout << "a的值为:" << a << endl;
 	//a在复合语句外不可见
 	//cout <<"a的值为:" << a << endl;
 	return 0 ;
}
 	

The example shows the case where variables are defined at the head of a conditional statement. a is visible in the conditional statement, and is automatically destroyed after the statement ends. If we delete the comment of the last print statement, the compiler will report an error because it cannot find the definition of a.
like this

#include<iostream>
using namespace std;
//复合语句的作用域
int main()
{
    
    
//复合语句
if ( int a = 0 )
	cout << "a的值为:" << a <<endl;
else
 	cout << "a的值为:" << a << endl;
 	//a在复合语句外不可见
 	cout <<"a的值为:" << a << endl;
 	return 0 ;
}
 	

The error is reported as:
insert image description here
Note When defining variables in the if statement, we also implicitly use the initial value of the variable as the condition of the if statement. The more common example of declaring variables at the head of a compound statement is the declaration of the first part of the for loop head that has appeared in the previous example, such as "for (int i= 0; i>=0; i++)" "int i= 0;", there is no hidden semantic problem here, even if it is an empty statement, the loop can still be executed as usual.

If this article is helpful to you, please like it and support it~

Guess you like

Origin blog.csdn.net/m0_62870588/article/details/123704732