The following code gives the output as : ccb
int t = 0;
char a[] = {'a', 'b', 'c'};
cout<<a[t]<<a[++t]<<a[++t];
I want to know, what actually is happening in this code which generates the specified output. Any help will be appreciated.
The following code gives the output as : ccb
int t = 0;
char a[] = {'a', 'b', 'c'};
cout<<a[t]<<a[++t]<<a[++t];
I want to know, what actually is happening in this code which generates the specified output. Any help will be appreciated.
My initial reaction: C++ does not guarantee the order of evaluation on a statement like
cout<<a[t]<<a[++t]<<a[++t];
You need to do something along the lines of:
cout<<a[t]<<a[t + 1]<<a[t + 2];
t += 3;
Upon further review, in response to R Sahu's comments (thanks): The order of evaluation may actually be determinate because operator << is a function call and a function call is a sequence point. However the order will not be as expected. In this case the t++
operations are executed in right-to-left order because the arguments to each function call must be evaluated before the call is made. I.e. this statement is actually:
cout ( << a[t] ( << a[++t] ( << a[++t] ) ) ) ;
and the innermost phrase is evaluated first.
Of course the above parenthesized expression is not valid. To be technically correct I should say:
operator << (operator << ( operator << ( cout, a[++t]), a[++t]), a[t]);
but that is confusing because in order to write the expression in this form I have to reverse the order of the index operators (which is what the compiler does).
And finally in response to Baum's comments: Even decomposing this into function calls this way does not make the call determinate because the order in which function arguments are evaluated is not specified so it could evaluate operator << (cout, a[++t])
before evaluating a[t]
The solution, avoiding operations with side-effects in complex statements, is still valid.
The order of evaluation is unspecified. https://en.wikipedia.org/wiki/Sequence_point