0
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    int a=1;
    printf("%d\t%d\t%d\n",a,++a,a++);
    return 0;
}

Why the output of the code is 3 3 1. someone explain me how this kind of output happen?

play store
  • 393
  • 1
  • 5

2 Answers2

1

Seems like your compiler reads the parameters from right to left

printf("%d\t%d\t%d\n",a,++a,a++); // a = 1

a++ returns a and increments it by 1

printf("%d\t%d\t%d\n",a,++a, 1); // a = 2

++a increments a by 1 and returns the result

printf("%d\t%d\t%d\n",a, 3, 1); // a = 3

a is just a

printf("%d\t%d\t%d\n", 3, 3, 1); // a = 3

But AFAIK this is kinda UB because the c++ standard doesnt rule in which order the parameters are read, so I wouldnt bet on it beeing the same on different compilers

Edit: With C++17 its no longer UB but unspecified. You should still avoid it

Narase
  • 490
  • 2
  • 12
  • please see the comment from [StoryTeller](https://stackoverflow.com/users/817643/storyteller) below my answer. It isn't always UB anymore. In C++17 it is unspecified. – Tarick Welling Jun 17 '19 at 08:32
  • Ive read it. But "unspecified" is just slightly better than UB. Compiler specific implementations should be avoided too – Narase Jun 17 '19 at 08:46
  • totally agreed, but your answer becomes better when it is included :) – Tarick Welling Jun 17 '19 at 08:48
  • your last 2 paragraphs could be reprhased a bit. When there is UB it does not just mean that you get them evaluated in unpredictable order, but UB is something the compiler may assume to never happen, hence before C++17 not only the outcome is undefined but the whole code could do anything, with C++17 you still dont know the order, but there is no UB, which is a fundamental difference – 463035818_is_not_an_ai Jun 17 '19 at 10:14
0

This is undefined behaviour as per the order of evaluation. reference (see chapter Undefined behavior)

The output is:

3 3 1

because it evaluates as follows:

a++
use a(1) and a becomes 2
++a
a becomes 3 and use a(3)
use a(3)

Important is to know that a++ is post-increment and ++a is pre-increment. Post-increment means: use the value and increase it after. Pre-increment means: increment the value and use the incremented value.

sidenote: C++17 changed this from undefined behaviour to unspecified but in previous versions it still is undefined behaviour.

Community
  • 1
  • 1
Tarick Welling
  • 3,119
  • 3
  • 19
  • 44