0
#include <stdio.h>

int main()
{
    int i = -1, j = -1;
    printf("%d %d %d \n", i++, ++i, ++i);
    printf("%d %d %d \n", ++j, ++j, j++);
    return 0;
}

output:

1 2 2
2 2 -1

to me it seems like the output should have been

-1 2 2
2 2 1

or something, but it is not the case. It seems like the compiler is executing the increments from right to left. return the rightmost j (-1) then increment it, increment leftmost and middle j's and then return (2), resulting in 2 2 -1. I thought compiler reads from left to right. Is there something I am missing? I dont think that this is undefined behaviour, because the output is consistent, I tried it many times and it yields the same result every time. The difference between this question and my question is that in my code, I dont make assignments to the original variable, and the incrementions are seperated with commas.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 3
    You do make assignement, but it's the same and a little worse. When you transmit parameters to a function the order their are computed is not defined. It is frequently from the last one to the first, but you do not know. So, **neither try to modify several times a variable in a single expression**. – dalfaB Jun 23 '23 at 14:25
  • 3
    "Undefined behavior" simply means that the compiler and runtime environment are not required to handle the situation in any particular way; it doesn't mean the results will vary from run to run. It can even give you the result you expect, which is what gets people in trouble - their code *appears* to work until they make a minor change (like adding a print statement for debugging), and then all of a sudden the code stops working. – John Bode Jun 23 '23 at 16:32
  • Thank you very much! This was a question in olympiad of informatics of Turkey, so I thought that they wouldn't put a question with undefined behaviour. But reading your comments, I see that you are right. Thanks! – Mustafa Aslan Jun 24 '23 at 15:02

0 Answers0