Dec 19, 2013 at 4:05pm UTC
const auto: I know auto ignores top level const but how do you fix this code
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
using std::cin; using std::string;
using std::cout; using std::endl;
int main()
{
const string s1("Hello World!!!" );
for (auto &c : s1) {}
cout << s1 << endl;
return 0;
}
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
using std::cin; using std::string;
using std::cout; using std::endl;
int main()
{
const string s1("Hello World!!!" );
for (const auto &c : s1) {}
cout << s1 << endl;
return 0;
}
Last edited on Dec 19, 2013 at 8:23pm UTC
Dec 19, 2013 at 5:12pm UTC
Auto does not ignore top level const. In the second case, you are just being explicit about it, but both auto references are const.
That s you are trying to iterate over doesn't exist. Did you mean s1 ?
Else, what do you mean by "how do you fix this code"?
Dec 19, 2013 at 5:26pm UTC
const
in const auto &c
is qualifying the referenced type, not the auto itself (it wouldn't work for a reference anyway).
const auto &
is actually quite common.
Dec 19, 2013 at 8:23pm UTC
Oh no sry about the s and s1. But if you compile that you get an error. Sry I'm on ipad and get get the error message
Dec 19, 2013 at 9:53pm UTC
I compiled both with no errors.
Dec 20, 2013 at 6:23pm UTC
Mmm strange. I got errors I'm gonna check and see whats the error.
Dec 20, 2013 at 6:32pm UTC
Tell us your compiler and version and the exact error message you get if you would.
Sorry I was grouchy with you the other day.