different types in for loop

can i do the following and how?

1
2
3
4
for (double it=0,int i=0;it!=5.0;++it,i++)
  {
	  ...
  }


different types of variables in the loop..
You can't initialize different types in a for loop;

Try this work around:
1
2
3
4
5
double it = 0;
for (int i = 0; it != 5.0; ++it, ++i)
{
  // code here
}
wolfgang? Why wouldn't he be able to do that? I personally never tried it, but do for loops explicitly prevent you from initializing variables of multiple types within the same statement? I always thought it was just using the , operator, and doesn't care about what exactly you write.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Test
#include <iostream>

using namespace std;
int main()
{
    for (int i = 0, double d = 0.0; i < 10; i++)
    {
      d += .4;
      cout << d << endl;
    }

    return 0;
}


C:\prgm\cpp\testing\trial.cpp||In function 'int main()':|
C:\prgm\cpp\testing\trial.cpp|7|error: expected unqualified-id before 'double'|
C:\prgm\cpp\testing\trial.cpp|9|error: 'd' was not declared in this scope|
||=== Build finished: 2 errors, 0 warnings ===|


You can't change the the comma to ; because then it thinks the double d is part of the condition. If there is a way to do so, I don't know it.
Last edited on
... I would say it's mostly a syntax thing. If you could write double it=0,int i=0 as legal syntax, then why not. But that's not the case, you have to have a semicolon, but that will break the syntax of the for-loop... There are probably many other things wrong, but that seems logical to me.
This, for example, is permitted. As far as I can know, there's no restriction on the condition other than it be a valid (single) statement.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Test
#include <iostream>

using namespace std;
int main()
{
    for (int i = 0, d = 0; i < 10; i++)
    {
      d +=1;
      cout << d << endl;
    }

    return 0;
}

Last edited on
True Moschops, but the "0.0" still gets cut to an int. If you want a double and an int in the loop, you are going to have to initialize one outside of the for statement.... I can't think of any other way currently.

-- edit: well, you changed it... apparently you saw it already
Last edited on
Yes. It was all completely legal, but I just knew someone would comment on the bad style :p
Topic archived. No new replies allowed.