mercredi 3 juillet 2019

Why is modification of auto iterated data not a syntax error?

I recently came to know that when a data inside range based for loop is modified, the result is undefined. So my question is that why isn't it a syntax error. Why do C++ compilers allow this when results are undefined for sure? As far as I understand, compilers should be able to classify which function calls modify data and which ones only read data. For example when i tried to sort elements of vector of vector, some elements were not sorted but the code ran successfully

vector<vector<int> > arr;
arr.push_back({38, 27});
for(auto v : arr)
{
    sort(v.begin(), v.end());
}

The output of above code after sorting is still 38, 27 after sorting. Whereas when i sort as sort(arr[0].begin(), arr[0].end()), the result is correct. I compiled using gcc.

Aucun commentaire:

Enregistrer un commentaire