怀疑'for'语句是如何工作的

时间:2012-12-20 13:44:37

标签: c++ for-loop declaration

有一些我对for语句没有理解的东西,在下面的代码块中请专注于???评价:

void user_interface::execute_a_command( const string& cmd, command cmd_table[] )
{
    LOG("user_interface::execute_a_command(): Executing \"",cmd,"\"");
    bool command_executed = false;
    //Exist any operation for this command?
    command* elem = &cmd_table[ 0 ]; //???
    for( int i = 0 ; cmd_table[ i ].function != nullptr ; i++, elem = &cmd_table[ i ] )
    {
        if( cmd == elem->name )
        {
            //Call the function
            (this->*(elem->function))();
            command_executed = true;
            break;
        }
    }

好吧,这段代码编译得很好,没有特别的警告。但是如果我将'elem'的声明和初始化放在'for'语句中,如下所示:

for( int i = 0 , command* elem = &cmd_table[ 0 ] ; cmd_table[ i ].function != nullptr ; i++, elem = &cmd_table[ i ] )

g ++ 4.7.2不会使用此错误编译此代码:

game.cpp:834:27:错误:在''令牌之前预期的初始化程序 game.cpp:834:27:错误:预期';'在''令牌

之前

我不清楚为什么。有人可以帮我理解这里的问题吗?

由于

4 个答案:

答案 0 :(得分:9)

您无法在初始值设定项中声明不同类型的变量。如果它们属于同一类型,它将起作用:

for (int ii = 0, jj = 1, kk = 2; ii < count; ++ii, --jj, kk += 15) {
    // ...

继续进一步说,多个变量声明要求它们具有相同的类型:

int a, b = 2, *c; // Yes
float x, double y, std::string z = "no"; // no

答案 1 :(得分:2)

for语句中的初始化可以定义多个变量,但所有变量都需要具有相同的类型。

答案 2 :(得分:1)

您不能使用逗号运算符执行不同类型的2个声明。

答案 3 :(得分:1)

以前的答案都是正确的并直接解决了你的问题,但我会提供我喜欢的风格,即在循环内直接声明一个“方便变量”:

for( int i = 0 ; cmd_table[ i ].function != nullptr ; i++ )
{
    command* elem = &cmd_table[ i ];
    if( cmd == elem->name )
    {
        //Call the function
        (this->*(elem->function))();
        command_executed = true;
        break;
    }
}

这提供了对cmd_table的“干净”访问权限,并且在循环结束后不会给您留下无效的elem。此外,没有性能影响这样做,因为它只是编译器将优化的指针。