Const auto reference in range for

closed account (EwCjE3v7)
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
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"?
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.
closed account (EwCjE3v7)
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
I compiled both with no errors.
closed account (EwCjE3v7)
Mmm strange. I got errors I'm gonna check and see whats the error.
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.
Topic archived. No new replies allowed.