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] << ' ';
  }
}

5 Answers 5

16

Try without the int before col.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you - I didn't notice this at all.
Can we perform logical operation between the two conditions pertaining to the variables i and j in placeholder for condition in the for loop?
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;.

1 Comment

That would be true - this was a simple test case I put together for the question. Good catch
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]]*;

2 Comments

The last sentence is not really true. For example, the following is valid: int w, *x, (*y)(int, int), z;
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 ! :)
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] << ' ';
  }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.