fatal error C1061: 编译器限制 : 块嵌套太深

VisualStudio开发过程中碰到C1061报错,查了MSDN,文档说明如下

从说明中我们明白这是由于我们的代码块嵌套太深,超过了编译器的限制。但我理解为应该是同一个域内块的数量太多,超过了编译器限制。示例代码如下:


void Demo1()
{
        for( int i = 0; i < 10; ++i ) { cout << i << " "; } cout << endl;
        …重复200个
        for( int i = 0; i < 10; ++i ) { cout << i << " "; } cout << endl;
}
void Demo2()
{
        int i =0;
        if( i == 1 ) { cout << i << endl; }
        else if( i == 2 ) { cout << i << endl; }
        …重复200个
        else if( i == 200 ) { cout << i << endl; }
}
void Demo3( int i )
{
        switch( i )
        {
        case 0 : { cout << i << endl; } break;
        ..重复200个
        case 200: { cout << i << endl; } break;
        default: { cout << "unknown" << endl; } break;
        }
}
void Demo4()
{
        for( int i = 0; i < 10; ++i ) cout << i << " ";
        …重复200个
        for( int i = 0; i < 10; ++i ) cout << i << " ";
}
void Demo5()
{
        { for( int i= 0; i < 10; ++i ) { cout << i << " "; } cout << endl; }
        …重复200个
        { for( int i= 0; i < 10; ++i ) { cout << i << " "; } cout << endl; }
}

  

Demo1

编译报错。

 

Demo2

编译报错。

 

Demo3

编译通过。

 

Demo4

编译报错。

Demo4Demo1的区别是少了for循环的大括号。

 

Demo5

编译通过。

Demo5Demo1的区别是给每个for循环块加上了一对大括号。

 

实验结果说明,代码中块的数量太多,会导致编译器报错。

 

 

解决方法

对于for循环块这样独立的代码块,可以给每个代码块加上一对大括号,这样每个代码块就有了一个独立的域。

对于if-else这样的代码,可以尝试改成switch-case格式。

最好的办法应该是将每个代码块封装成类或函数调用,这样可以简化代码的复杂度,也显得更加优雅。

 

 

扩展

之前碰到一个问题,代码如下:

 

if( condition)
{
        do something
}
else if( condition)
{
        if( condition)
        {
                CDemoClassdc;
                dosomething with dc
        }
}

编译死活报错,将声明dc那一行移到外面去就编译通过:

if( condition)
{
        do something
}
else if( condition)
{
        CDemoClassdc;
        if( condition)
        {
                dosomething with dc
        }
}

因为没及时记录,忘记报错的内容了。个人猜测,这可能也跟块嵌套太多有关系。

 

 

参考

https://msdn.microsoft.com/zh-cn/library/dcda4f64(v=vs.140).aspx

http://stackoverflow.com/questions/11508013/blocks-nested-too-deeply

http://stackoverflow.com/questions/4009923/c-fatal-error-c1061-with-large-switch-metaprogramming

posted on 2016-12-25 00:40  昵称还得唯一  阅读(1353)  评论(0编辑  收藏  举报