What is (const auto& i) in C++ ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

6th Apr 2018, 1:57 PM
777
777 - avatar
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
6th Apr 2018, 5:28 PM
AZTECCO
AZTECCO - avatar
+ 8
Thank you very much Rahul ! Nice to help :)
7th Apr 2018, 8:09 AM
AZTECCO
AZTECCO - avatar
+ 7
Thank you JPM7 ! You know your stuffs! Clear explain 👍
6th Apr 2018, 7:24 PM
AZTECCO
AZTECCO - avatar
+ 3
It is pointer on memory which array allocate and it iterate through this memory.
6th Apr 2018, 2:02 PM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 3
Thanks for your great explanation, AZTECCO !
7th Apr 2018, 6:16 AM
777
777 - avatar
+ 2
@Bartosz Pieszko, could you explain me more (especially the "auto" keyword) ?
6th Apr 2018, 2:06 PM
777
777 - avatar
+ 2
Auto replace type of this memory (int, char etc..). It autodetects which type of variables are used.
6th Apr 2018, 2:07 PM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 1
AZTECCO Then for ((const auto&) el : arr) is the same as for (auto el : arr)? Works the same.
6th Apr 2018, 5:32 PM
Bartosz Pieszko
Bartosz Pieszko - avatar
+ 1
JPM7 Ohh, I understand now. Thank you. 🙂
6th Apr 2018, 6:00 PM
Bartosz Pieszko
Bartosz Pieszko - avatar