首页 > 解决方案 > 函数或代码中间的代码块

问题描述

像下面的例子一样,在函数或程序中间有代码块是什么意思?

#include <iostream>
#include <string>
using namespace std;

int main(){
    int x = 32;

    { // random code block starts here

        if (34 > x){
            cout <<"x greater"<<endl;
        }else cout << "no\n";

    }// ends here

    return 0;

}

标签: c++c++11

解决方案


据我所知,这会创建一个新的scope,因此在其中声明的任何对象或变量{}都只能在那里使用。这对于创建实例特别有用,objects因为destructor对象超出范围时将被调用。

但是,在这种情况下,不需要 ,{}因为没有声明变量或创建对象。


推荐阅读