Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was learning about range based for loops in c++ and I came across this code:
int somenum[] = {1, -101, -1, 40, 2040 };

for (const int& aNum : somenum)
cout << aNUm << endl;

what I didn't understand is why they used const int& aNum instead of auto aNum or int aNum. Can anyone help me?

What I have tried:

I searched it up to find that the & was a reference pointer or something, but I still don't understand
Posted
Updated 22-May-21 1:37am

1 solution

The addition of const ensures you will get compilation errors if you try to change the value of the referenced value inside the loop, is all. If they values shouldn't change, or you are passing them to a function that expects a const value, it makes sense.

But your code won't compile: aNum and aNUm are different variables!

With that corrected, in the specific case of your code as shown, you could use either:
C++
int somenum[] = {1, -101, -1, 40, 2040 };
for (const int& aNum : somenum)
   cout << aNum << endl;
Or
C++
int somenum[] = {1, -101, -1, 40, 2040 };
for (int aNum : somenum)
   cout << aNum << endl;
Because you aren't passing it to anything that would modify it.


There is a lot more detail here: c++ - int vs const int& - Stack Overflow[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900