Search code examples
c++arraysfunction-call

How the values of array got affected in the following c++ code?


When the following program is compiled, the output is if break float while break.

#include<iostream>
using namespace std;

string s[5]={"if","int","float","while","break"};
string & blast(int i){ return s[i];}
int main()
{
    for (int i = 0; i < 5; i++ )
         if( i % 3 == 1 )
             blast( i ) = s[ 5-i ];
    for (int i = 0; i < 5; i++ )
        cout << s[ i ] << " ";
    cout<<endl;
    return 0;
}

Attempt:

blast[1] = s[4] = "break"
so, s[1] = "break"
Then blast[4] = s[4] = s[1] = "int"

but output doesn't agree with this.

I didn't understand this.. Please help me out.


Solution

  • As you wrote yourself you have when i is equal to 1

    blast[1]= s[4] = "break"
    so, s[1] = "break"
    

    Thus s[1] contains the string "break". After that the array does not contain the string "int". Then this string "break" is copied now from s[1] to s[4] when i is equal to 4

    blast[4]= s[4] = s[1] = "break"