12

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've looked over documentation for how a for-loop should look and I'm still confused. What's wrong here?

#include <iostream>
#include <vector>

int main() { 
std::vector<int> values; 

for (int i = 0; i < 20; i++) { 
  values.push_back(i); 
}   

std::cout << "Reading values from 'std::vector values'" << std::endl;
for (int i = 0, int col = 0; i < values.size(); i++, col++) {
  if (col > 10) { std::cout << std::endl; col == 0; }
  std::endl << values[i] << ' ';
  }
}
jdphenix
  • 15,022
  • 3
  • 41
  • 74

5 Answers5

16

Try without the int before col.

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

jweyrich
  • 31,198
  • 5
  • 66
  • 97
7

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;.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

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]]*;

Chethan Ravindranath
  • 2,001
  • 2
  • 16
  • 28
  • 1
    The last sentence is not really true. For example, the following is valid: `int w, *x, (*y)(int, int), z;` – James McNellis Jan 09 '12 at 04:29
  • I agree! I couldn't find the c++ standards' definition of variable declaration. Hence have given an abstract representation of a var declaration. here variable name doesn't strictly confirm to [a-zA-Z][a-zA-Z0-9]*. It can also mean *x, e.g. int w = 10, *x = NULL; Thanks for clarifying ! :) – Chethan Ravindranath Jan 09 '12 at 04:39
2

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] << ' ';
  }
}
Kalpesh Patel
  • 2,772
  • 2
  • 25
  • 52
1

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
def
  • 521
  • 4
  • 16