lundi 28 novembre 2016

Using C++11 auto keyword in for-loop to declare two (or more) variables

I have code like this:

for (auto i = modelList->size() - 1, j = -1; i >= 0; --i) {
    ...;
}

When I compile it with g++ (v.6.2.1) I get the following error:

error: inconsistent deduction for ‘auto’: ‘auto’ and then ‘int’

I'd understand this, if variables had different types like auto i = 0.0, j = 0;, but in this case modelList is QList and its size() method returns int, -1 on its own should be int, too. The error message is a bit strange as well.

Variables i and j are only needed in this loop and I'd like to declare them as loop parameters. It's not hard to type int instead of auto, but I'd like to know: is auto not supposed to be used for declaring multiple variables in one go, or I am missing something here and it really is erronous code, or maybe it is the compiler's bug?

Aucun commentaire:

Enregistrer un commentaire