about for loops

Hey everyone,

I have a quick question about using for loops. if you initialize your control variable inside the loop body, and test it against a condition that yields a different data type, is this considered bad form?

my example:

1
2
3
4
void displayVect(vector<double> v){
for(int i = 0; i < v.size(); ++i)
...
} 


Is it better to have the control variable a double in this case?

Thanks
Is it bad form to compare two values that are different data types?
yes, and in some cases, it can lead to compile time errors or undefined behavior.

Is it better to have the control variable a double in this case?

No. In this case, it is better to iterate over the values in the vector.
1
2
3
4
5
6
void displayVect( vector<double> v)
{
   vector<double>::iterator iter;
   for( iter=v.begin(); iter != v.end(); ++iter)
      std::cout << *iter << std::endl;
}


or, in C++11,

1
2
3
4
5
void displayVect(vector<double> v)
{
   for(const auto& elem : v)
      std::cout << elem << std::endl;
}


http://www.cplusplus.com/reference/stl/vector/begin/
http://www.cplusplus.com/reference/stl/vector/end/
Last edited on
Thanks for the response,
I have learned that format before and now I see the benefit of using it.
Thanks atropos
Topic archived. No new replies allowed.