-3

the code is given below: it gives output true2.

    #include<stdio.h>
    int main()
    {
    int a=10;
    if(a==a--)
    printf("true 1\t");
    a=10;
    if(a==--a)
    printf("true2 \t");
    return 0;
    }
  • 2
    The output *can't* be explained because you have [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). Read about [evaluation order and sequencing](http://en.cppreference.com/w/c/language/eval_order). – Some programmer dude Sep 30 '16 at 16:44
  • 2
    This is a pointless junk, not a code. (Sorry). What is it expected to show? – Eugene Sh. Sep 30 '16 at 16:44
  • for ease of readability and understanding, 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. 2) separate code blocks (for, if , else, while, do...while, switch, case, default) via a blank line – user3629249 Sep 30 '16 at 16:47
  • 1
    when compiling, always enable all the warnings, then fix those warnings. (for `gcc`, at a minimum use: `-Wall -Wextra -pedantic` I also use: `-Wconversion -std=gnu99` ). Compiling with the warnings enabled will produce two instances of: `warning: operation on 'a' may be undefined [-Wsequence-point]` One each for line 5 and line 8 – user3629249 Sep 30 '16 at 16:52

2 Answers2

2

The comparison done in both of the if statements result in undefined behaviour. So, anything could happen. Because a is read and modified without an intervening sequence point. The comparison operator == doesn't introduce a sequence point. You probably need to learn about undefined behaviour and sequence points, etc to understand the problem better.

Modern compilers may also help you. For example, Clang issues:

warning: unsequenced modification and access to 'a' [-Wunsequenced]
    if(a==a--)
       ~   ^
warning: unsequenced modification and access to 'a' [-Wunsequenced]
    if(a==--a)
       ~  ^

for the two if statements (GCC also produces similar warnings with gcc -Wall -Wextra).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.P
  • 117,907
  • 20
  • 175
  • 238
0

In general, it is not a good practice to do a-- (or --a) inside a condition, because it is not clear to read. In order to understand the difference between a-- and --a please see the answer at: Incrementing in C++ - When to use x++ or ++x?

Community
  • 1
  • 1
Idan
  • 333
  • 2
  • 8