+ 3
What is (const auto& i) in C++ ?
Hi, I have the following code: #include <iostream> using namespace std; int main() { int arr[4] = {1, 2, 3, 4}; for(const auto& i : arr) { cout << i << " "; } return 0; } // outputs 1 2 3 4 Now, what is const auto& i and what it is doing behind the scenes?
9 Answers
+ 8
auto& is auto detection (like Bartosz Pieszko said) plus & is reference..
so you can see il like int& or char&.
the interesting thing here is the const keyword before.. this is not a const reference.. the reference is const by itself, this const is about the object the reference refers to.
This means the iterator cannot modify the data, can only 'read'
If you try something like
i = something
inside the loop..
the compiler will complain.
So your data is protected, and bugs will rise immediately if you accidentally type a wrong comparing for example..
if(i = 0)do something ==>error I is reference to const or const reference .
I tried to do my best to explain , hope it helps
+ 8
Thank you very much Rahul !
Nice to help :)
+ 7
Thank you JPM7 ! You know your stuffs!
Clear explain đ
+ 3
It is pointer on memory which array allocate and it iterate through this memory.
+ 3
Thanks for your great explanation, AZTECCO !
+ 2
@Bartosz Pieszko, could you explain me more (especially the "auto" keyword) ?
+ 2
Auto replace type of this memory (int, char etc..). It autodetects which type of variables are used.
+ 1
AZTECCO
Then for ((const auto&) el : arr) is the same as for (auto el : arr)?
Works the same.
+ 1
JPM7
Ohh, I understand now. Thank you. đ