Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for-loop structure with multiple variable initialization

Tags:

c++

for-loop

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] << ' ';
  }
}
like image 645
jdphenix Avatar asked Jan 09 '12 04:01

jdphenix


4 Answers

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
like image 182
def Avatar answered Sep 30 '22 01:09

def


Try without the int before col.

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

like image 16
jweyrich Avatar answered Oct 20 '22 01:10

jweyrich


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

like image 7
Jerry Coffin Avatar answered Oct 20 '22 01:10

Jerry Coffin


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

like image 3
Chethan Ravindranath Avatar answered Oct 20 '22 00:10

Chethan Ravindranath