2
votes

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.

1
Hint: What happens if you assign to a mutable reference?tadman
string &blast (int i) returns a reference to the string within the array to which you then assign a new string, e.g. blast(i) = s[5 - i]; is the same as s[i] = s[5 - i]; Additionally, if you space your code a little more, it will be a lot more readable (especially for older eyes), e.g for (int i = 0; i < 5; i++) and if (i % 3 == 1), etc..David C. Rankin
Did you possibly want to std::swap(blast(i), s[5-i]);?Aconcagua
Please keep an eye on appropriate formatting. Code gets much more readable that way. I fixed line breaks and indentation for you, still your parentheses follow inconsistent patterns. Having spaces after opening or before closing parentheses is rather unusual, but I don't care too much if you at least keep it consistent (either both or none – and then for all pairs the same). Spaces around operators should always be placed.Aconcagua
About braces: I recommend to place them, even if not needed, at least if an expression contains more than two lines (like the first for loop after my edit), and for all blocks of an if-else chain, if at least one of them needs them. There are coding conventions (like MISRA) always mandating braces, which makes your code robust e. g. against badly written macros (not very meaningfull, admitted, but perhaps something likeINCREMENT_BOTH(X, Y) ++X; ++Y;) or against forgetting to place them on adding further expressions.Aconcagua

1 Answers

1
votes

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"