1

I have been trying to figure out why the output of the code below is 2 2 but can't seem to figure out why. I get that the else statement is getting executed but from what I've read I can't understand why the first print doesn't get executed.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 1, y = 1;

    if(x++ == y++)
        printf("%d%d", x--, y--);
    else
        printf("%d%d", x,y);
    return 0;
}

Originally I expected the output to be 0 0

I have played around with changing the values and the operators and each time the decrement print never executed. From what I can tell from reading on the topic decrementing inside a print should be possible but I'm not sure what is making it not execute.

3 Answers3

3

The if block is being executed.

In the condition if(x++ == y++), the current value of x is compared with the current value of y. Both are 1 so the comparison is true, and both x and y are incremented as a side effect.

So then this statement runs:

printf("%d%d", x--, y--);

Which prints the current values of x and y which are both 2, and both are decremented as a side effect. If you were to print both after this, you would see that both are 1.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

In order to understand your code, you might do the following:

int main()
{
    int x = 1, y = 1;

    printf("x=%d, y=%d", x,y);
    if(x++ == y++)
    {
        printf("x=%d, y=%d", x,y);
        printf("x--=%d, y--=%d", x--, y--);
        printf("x=%d, y=%d", x,y);
    }
    else
        printf("x=%d, y=%d", x,y);
    return 0;
}

Dominique
  • 16,450
  • 15
  • 56
  • 112
-1
#include <stdio.h>
#include <stdlib.h>

int main()

{
   int x = 1, y = 1;

   if(x++ == y++)               // here x and y become 2
    printf("%d%d", x--, y--);   // x with postfix decrement x and
                                //  returns the initial value 
   else
    printf("%d%d", x,y);
  return 0;
}

lot of help You get my recomendation use prefix ++x

  • Why would using the prefix increments alter things? The comparison would compare `2` vs `2` whereas the original (postfix increments) compares `1` vs `1`, but it's not clear that matters. – Jonathan Leffler Dec 08 '22 at 16:27
  • [learncpp](https://www.learncpp.com/cpp-tutorial/increment-decrement-operators-and-side-effects/) I guess this could help you to understand difference post-- and pre-- . and sorry about error, yes you are right that is decrement, fixed it – Gints Misins Dec 08 '22 at 19:24