C++ for-loop structure with multiple variable initialization

后端 未结 5 1433
长情又很酷
长情又很酷 2021-01-17 12:01

On the 2nd for-loop, I get the following error from gcc:

error: expected unqualified-id before \'int\'

I\'m not sure what I\'m missing. I\

相关标签:
5条回答
  • 2021-01-17 12:03

    Try without the int before col.

    for (int i = 0, col = 0; i < values.size(); i++, col++)

    0 讨论(0)
  • 2021-01-17 12:21

    Others have already told you how to fix the problem you've noticed. On a rather different note, in this:

    if (col > 10) { std::cout << std::endl; col == 0; }
    

    It seems nearly certain that the last statement here: col==0; is really intended to be col=0;.

    0 讨论(0)
  • 2021-01-17 12:25

    This should fix it

    for (int i = 0, col = 0; i < values.size(); i++, col++) {
      if (col > 10) { std::cout << std::endl; col == 0; }
      std::endl << values[i] << ' ';
      }
    }
    

    A variable definition goes like this

    datatype variable_name[=init_value][,variable_name[=init_value]]*;

    0 讨论(0)
  • 2021-01-17 12:25

    This is akin to a regular multiple variables declaration/initialization in one line using a comma operator. You can do this:

    int a = 1, b = 2;
    

    declaring 2 ints. But not this:

    int a = 1, int b = 2;   //ERROR
    
    0 讨论(0)
  • 2021-01-17 12:29

    Don't declare int after comma use,

    for (int i = 0,col = 0; i < values.size(); i++, col++) {
      if (col > 10) { std::cout << std::endl; col == 0; }
      std::endl << values[i] << ' ';
      }
    }
    
    0 讨论(0)
提交回复
热议问题