-10

So here's the question. Find the output for the following code. perform in c++

#include<iostream>
 using namespace std;
 int main()
 {
 int i=2;
 cout<<i++<<i<<i++<<i;
 cout<<i;
 }

This concept is based on post/pre increment operator. Based on this concept I predicted the output as 23344. Like I expected it was correct when I tried debugging this code. But without debugging i am getting the output as 34244. Is this even possible? BTW I tried this on Dev-C++ 5.11. Thanks :)

user0042
  • 7,691
  • 3
  • 20
  • 37
  • 1
    See [What not to ask](https://stackoverflow.com/tags/c%2b%2b/info) please. – user0042 Dec 03 '17 at 17:09
  • 1
    [`using namespace std;` is a bad practice](https://stackoverflow.com/q/1452721/2176813), never use it. – tambre Dec 03 '17 at 17:11
  • Hold on guys. I just need to know if the answer 23344 is correct or 34244 is correct. That's all. – I_love_coding Dec 03 '17 at 17:12
  • @user0042 I'm concerned that we're linking to a duplicate that is only tagged for c, not c++. – wally Dec 03 '17 at 17:12
  • @user0042 done! – I_love_coding Dec 03 '17 at 17:13
  • It doesn't matter; it's undefined behaviour in both languages. –  Dec 03 '17 at 17:14
  • 2
    @I_love_coding There's no _correct_ answer for this. And that's certainly not c code. – user0042 Dec 03 '17 at 17:14
  • This is guaranteed to output `23344` in C++17. Specifically, it's covered by point 19 [here](http://en.cppreference.com/w/cpp/language/eval_order). Just thought I should mention it what with all the "unconditionally undefined behaviour" talk. – chris Dec 03 '17 at 17:15
  • @chris [Interesting to see](http://en.cppreference.com/w/cpp/language/eval_order) how C++17 handles this. – wally Dec 03 '17 at 17:23
  • Both answers are correct. 42 would also be correct. The behavior is undefined, which means that the language definition does not tell you what the effect of that code is. – Pete Becker Dec 03 '17 at 17:26
  • 1
    https://stackoverflow.com/q/38501587/1460794 – wally Dec 03 '17 at 17:47

1 Answers1

0

Your construction invokes Undefined Behavior.

See Undefined behavior in c/c++: i++ + ++i vs ++i + i++ and Why are these constructs (using ++) undefined behavior?

 #include<iostream>

 using namespace std;
 int main()
 {
 int i=2;

 //cout<<i++<<i<<i++<<i; // UB! 

  cout<<i++; 
  cout<<i;
  cout<<i++;
  cout<<i;

  return 0;
}
sg7
  • 5,365
  • 1
  • 30
  • 39
  • I wanted to add that code,but felt it was irrelevant. I tried that too but again it gave different output when i tried it with and w/o debugging. As of now like other experts have mentioned i believe it is due to undefined behaviour. But again thanks for the help. – I_love_coding Dec 03 '17 at 17:44