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?
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?
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
?
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!
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.