首页 > 解决方案 > C++ - 循环初始化的奇怪问题

问题描述

编译器甚至无法处理最简单的循环

#include <iostream>
using namespace::std;

int main()
{

    for( int i = 0, char a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

编译器这样说:

prog.cpp: In function ‘int main()’:
prog.cpp:7:18: error: expected unqualified-id before ‘char’ 
prog.cpp:7:18: error: expected ‘;’ before ‘char’ 
prog.cpp:7:39: error: expected ‘)’ before ‘;’ token 
prog.cpp:7:41: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive] 
prog.cpp:7:41: note: (if you use ‘-fpermissive’ G++ will accept your code) 
prog.cpp:7:46: error: ‘a’ was not declared in this scope 
prog.cpp:7:50: error: expected ‘;’ before ‘)’ token

是的,我知道我可以在循环之前初始化“i”和“a”。所以让我们试试:

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;

    for(i = 0, char a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

编译器说:

prog.cpp: In function ‘int main()’:
prog.cpp:8:13: error: expected primary-expression before ‘char’
prog.cpp:8:13: error: expected ‘;’ before ‘char’
prog.cpp:8:41: error: ‘a’ was not declared in this scope

当使用选项 -std=c++11 时:

prog.cpp: In function ‘int main()’:
prog.cpp:7:17: error: expected unqualified-id before ‘char’
prog.cpp:7:17: error: expected ‘;’ before ‘char’
prog.cpp:7:38: error: expected ‘)’ before ‘;’ token
prog.cpp:7:40: error: ‘i’ was not declared in this scope
prog.cpp:7:45: error: ‘a’ was not declared in this scope
prog.cpp:7:49: error: expected ‘;’ before ‘)’ token

最后一个:

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;
    char a = 'A';

    for(i = 0, a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

工作正常。伙计们,我是瞎了吗?也许你需要我的 Arch 和编译器版本:

uname -a
Linux freelancer 3.2.0-4-686-pae #1 SMP Debian 3.2.63-2+deb7u2 i686 GNU/Linux
g++ --version 
g++ (Debian 4.7.2-5) 4.7.2

标签: c++loopsinitializing

解决方案


您不能在同一声明中声明不同类型的项目。

在循环内部和外部都是如此。你不是“盲人”,它只是无效的 C++。

这是正确的代码:

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;
    char a = 'A';

    for(; i <= 26; i++, a++ )

        cout << "OK, lets try. Showing values: i = "
            << i << ", a = " << a << endl;
}

您的工作版本也是有效的,因为可以将声明换成表达式,但在您的情况下它是多余的,因为这些变量已经在循环开始时保存了这些值。


推荐阅读