0

The following piece of code

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
 
int main() {
    // your code goes here
    string a="abc", b="xyz";
    a,b = a+b, b+a;
    cout<<a<<" "<<b<<endl;
    return 0;
}

outputs

abc abcxyz

Why is it so? Expected or desired output is

abcxyz xyzabc

How to get this?

Quimby
  • 8,111
  • 3
  • 18
  • 35
illla
  • 63
  • 6
  • 2
    TL;DR: Here `a,b = a+b, b+a;` essentially does `a; b = a+b; b+a;`. You'll need to use `std::tie` or something similar. – HolyBlackCat Jul 29 '20 at 11:01
  • 1
    Also please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – HolyBlackCat Jul 29 '20 at 11:02
  • as mentioned in https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do, a,b will evaluate to b i.e only b will be updated,right? then a+b,b+a will evaluate to b+a so b should be updated as b+a which is "xyzabc", but which is not happening!! please open this question!! or answer in comment. – illla Jul 29 '20 at 11:05
  • 2
    No, actually here ```=``` has higher precedence over ```,```, that's the reason it evaluates as @HolyBlackCat said – Sai Sreenivas Jul 29 '20 at 11:08
  • oh,then (a,b) = (a+b,b+a) does what i said in comment, got it – illla Jul 29 '20 at 11:12

0 Answers0