The following example seems to be very easy and straightforward:
void ftest(size_t& arg)
{
std::cout << arg << '\n';
}
int main()
{
size_t max = 5;
for (auto i = 0; i < max; ++i)
ftest(i);
}
but it won't compile (at least using VS2013) because the i is deduced as int and not as size_t. And the question is -- what is the point of auto in such for-loops if it can't rely on the conditional field? Would it be too much hard and time consuming if a compile analyze the whole statement and give expected result instead of what we're having now?
Because the type of variable is determined when declared (from its initializer), it has nothing do with how it will be used. If necessary type conversion would be considered. The rule is same as variables declared with type specified explicitly, auto
is just helping you to deduce the type, it's not special.
Try to consider about this:
auto max = 5u;
for (auto i = 0; i < max; ++i)
// ~~~~~~~~
// i should be unsigned int, or max should be int ?
BTW: You could use decltype
if you want the type to be determined by the conditional field max
:
for (decltype(max) i = 0; i < max; ++i)