daboor
daboor

Reputation: 33

Use of & operator in C++ Range Based Loop ..Confusing

char SArray[6]={'a','b','c','d','e','\0'};
for(char n: SArray) {
  n = 'R';
}
for (int i =0;i<7;i++) {
  cout << "Slot " << i << ":" << SArray[i] << endl;
}
Slot 0:a
Slot 1:b
Slot 2:c
Slot 3:d
Slot 4:e
Slot 5:
Slot 6:R

If loop is written this way for(char n: SArray), C++ puts 'R' After the array, to the next address(i checked addresses too)

If we declare n reference

for(char &n: SArray)

then its all good

Slot 0:R
Slot 1:R
Slot 2:R
Slot 3:R
Slot 4:R
Slot 5:R
Slot 6:╖

What does this expression do exactly? for(char n: SArray) And here, for(char &n: SArray), &n, reference for what? i thought references can be created only to existing variables

Thank you!

Upvotes: 0

Views: 222

Answers (2)

Ian Ash
Ian Ash

Reputation: 1212

When you use the & operator in a range based loop, you are telling the compiler you want to directly access the elements of the range. I.e. in your example, you directly modify each element in SArray.

When you do not use the &, you are asking the compiler to make a local copy of that element within the scope of the loop. In this case, when you write to n it does not update the actual element in the range, just the temporary variable, and so when the loop terminates the original array is unmodified.

So in general you use the & operator when your loop needs to update the range, and you leave out the & when you want the range to just be an input to the loop and not be updated.

You should also be aware of the syntax for (const &n : SArray) which gives read only direct access to an element in the range. A reason to use this syntax is when the elements of the range are large (e.g. a big struct) so you don't want to copy the data unnecessarily but you want to guard against an inadvertent write.

Upvotes: 3

user5550963
user5550963

Reputation:

My suggestions are: First learn references & operator. But let me try to explain in a simple way than we can go more complex and explain the loop.

& represents reference and in simple terms references is different name for the same variable. For example

int a = 5;
int& b = a;

b is different name for a. Next example:

int a = 2;
int b = 3;
int c = 5;

int& ref = a; // ref is different name for a
int& ref = b; // ref is now different name for b
int& ref = c; // ref is now different name for c

now lets put this analogy into your question:

char SArray[6]={'a','b','c','d','e','\0'};                                                         
for(char &n: SArray)
{
    n='R';
}

as loop goes on char &n refers to SArray[i] (is the name of SArray[i])

where as

char SArray[6]={'a','b','c','d','e','\0'};                                                         
for(char n: SArray)
{
    n='R';
}

copies SArray[i] to new variable n

Upvotes: 2

Related Questions