0
#include <stdio.h>

int main(void) 
{
    int a = 10;
    if(a == a--)
    {
        printf("TRUE 1");
    }
    a = 10;
    if(a == --a)
    {
        printf("TRUE 2");
    }
    return 0;
}

I thought this code should print TRUE 1 but rather the output is TRUE 2. Why is it so? It seems it only happens in C because the same thing in java prints TRUE 1.

  • 4
    I think this rather pointless exercise exhibits *undefined behaviour* in C. It's like asking "does this glass of juice hold the same amount *before* or *after* I drink from it?" – Weather Vane Mar 19 '20 at 19:19
  • [See also](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). Java defines some behaviors that C leaves undefined. – user3386109 Mar 19 '20 at 19:24
  • These kinds of post/predecrement questions are asked very often. I wonder if it is because of incompetent teachers. – Jabberwocky Mar 19 '20 at 19:25
  • 2
    @Jabberwocky some of the duplicate questions are so uncannily similar I wonder if there is some duff teaching material passed around. – Weather Vane Mar 19 '20 at 19:27
  • "`I thought this code should print TRUE 1 but rather the output is TRUE 2. Why is it so?`" When you say something like this, it is very helpful if you explain your reasoning. Obviously, your reasoning is incorrect, but it's hard for us to do a good job of explaining what you got wrong if you don't explain your reasoning. This question was closed as a duplicate of a question it may not be a duplicate of at all because someone assumed the issue was that you didn't realize this was UB. But it could, for example, be that you don't realize that `--a` modifies `a`. How can we tell? – David Schwartz Mar 19 '20 at 19:33
  • @DavidSchwartz interesting point. I see the code sets `a = 10;` between the two tests, so maybe there is a thought that there might be more than one value involved. – Weather Vane Mar 19 '20 at 19:38
  • For a bit more clarification - the results will vary with different compilers. Visual C++ prints both "TRUE 1" and "TRUE 2", while gcc just prints "TRUE 2". What's going on is that the C language specification doesn't spell out what order the two terms of "==" should be evaluated. Code carefully! – Steve Mar 19 '20 at 19:40
  • For a bit more clarification - the results will vary with different compilers. Visual C++ prints both "TRUE 1" and "TRUE 2", while gcc just prints "TRUE 2". Delving into the generated assembly code, Visual C++ saves the value of a in a temporary variable, saves a in another temporary variable, decrements a in memory, and compares the two temporary variables. gcc just creates one temporary, so the value being compared is actually the decremented value of 9. As other commenters have pointed out, the C language specification doesn't spell out what order the two terms of "==" are be evaluated. – Steve Mar 19 '20 at 19:48

0 Answers0