1

So my question is simply, can something like this work:

int size = 100;
for(int i : size)
  // bla

And if not, could you briefly explain why?

G.Rassovsky
  • 774
  • 1
  • 10
  • 23

3 Answers3

2

No, that does not work. A number is not a range. How would you define begin(100) or end(100) (which is what the range-based for loop calls internally)?

My guess is you'd want this as a shorthand for a loop from 0 to 99. But why not one from -2147483648 (or whatever std::numeric_limits<int>::min() is on your implementation) to 99?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

No this will not work!

Range-based loop works only on collections, which int is not.

Moreover, if you are comparing it with a normalfor loop, where is the initialization (i=0) statement and comparison (i<size) statement for i? The construct does not tell when to start the loop and when to end!

CinCout
  • 9,486
  • 12
  • 49
  • 67
1

No. Range-based for-loop are introduced for iterating through a collection, not some arbitrary range. Running a loop for a range of values can be achieved by using for, while or do-while. If you need such loop, for regular activities, that can be implemented by simply wring a function, a macro, that may take a function, functor, or lambda.

Ajay
  • 18,086
  • 12
  • 59
  • 105