0

The following code gives a weird output. I have tried it on multiple compilers and ended up with the same answer. It will process the statement right to left but print the output left to right however c++ statements are evaulated left to right in general. Can someone explain why this happens when we overload the cout statement.

Output: 15 10 5

However the Output if processed from left to right should be: 8 10 12

#include<iostream>
using namespace std;

int main(){
    int a = 5, b = 3, c = 2;
    cout<< (a = b + a) << endl << (b = c + a) << endl << (c = b  + c);
    return 0;
}
  • I agree on the unspecified behavior but it relates to sequence points altogether. If you can find a better one be my guest, otherwise we might reopen it. – Marco A. Sep 30 '15 at 14:26
  • Here is a near duplicate: http://stackoverflow.com/questions/2603312/the-result-of-int-c-0-coutcc – Paul R Sep 30 '15 at 14:29
  • Thanks for the answers everyone. Sorry im new here so i tried searching according to my limited knowledge but didnt find any suitable question. – Talha Zubair Sep 30 '15 at 14:32

1 Answers1

2

This will result in unspecified behavior. The order in which the operations execute isn't specified (since there are no sequence points between them), so the three assignments

a = b + a
b = c + a
c = b + c

can occur in any order. Therefore the output from cout is also unspecified .

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Right. The order in which the `<<`'s occur is specified. The order in which the values to output are evaluated is unspecified. Note that if two of the expressions modified the same variable, the result would be undefined and not unspecified. – David Schwartz Sep 30 '15 at 14:25