-1

Why n++==--n always equal to 1? The following code gives output as 1.

#include <stdio.h>
int main(){
    int n=10;
    printf("%d\n",n++==--n);
}

The output is always 1, no matter what n is.

  • The operator `==` produces a boolean value, in your case `true` that is converted to the value `1` by the `printf()`. If you try to `printf()` a `false`, you'll get a value of `0` – Yusef Maali Jun 04 '20 at 05:51
  • 3
    This is an undefined behaviour. If you enable all warnings, the compiler even may warn you about it. https://godbolt.org/z/SuAiyk – Alex Lop. Jun 04 '20 at 05:52
  • @AlexLop. Why it is an undefined behaviour? – Shubham Jun 04 '20 at 06:08
  • 1
    @Lucas because `==` doesn't introduce a sequence point, thus either left or right sides can be evaluated first and the standard doesn't define it ==> undefined behaviour. – Alex Lop. Jun 04 '20 at 06:10
  • But @AlexLop. , can't you go with the standard Operator Precedence and Associativity introduced in ANSI C? – Shubham Jun 04 '20 at 06:11
  • 2
    @Lucas not really. If you had `x + y++ - z`, based on the precedence `y++` would be executed first and then, by associativity `(x + y) - z`. `==` doesn't introduce a sequence point, it checks that both sides are equal (or not) no matter what you evaluate first. Thus, by the way, in case of function output compare `foo() == boo()` either `boo()` or `foo()` will be executed first. You cannot rely on the execution order here. – Alex Lop. Jun 04 '20 at 06:20
  • I got it. Thanks for explaining. @AlexLop. By the way, there's a conflict between ur 1st expression and 2nd expression. ```(x + y) - z```. – Shubham Jun 04 '20 at 06:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215279/discussion-between-lucas-and-alex-lop). @AlexLop. Can we chat? – Shubham Jun 04 '20 at 06:34

1 Answers1

3

If compiled with gcc -Wall, the following warning is obtained:

a.c: In function ‘main’:
a.c:4:20: warning: operation on ‘n’ may be undefined [-Wsequence-point]
     printf("%d\n",n++==--n);
                   ~^~

There is a good explanation in the gcc manpage about this, the section which begins:

       -Wsequence-point
           Warn about code that may have undefined semantics because of violations of sequence
           point rules in the C and C++ standards.

[...etc...]

which is well worth a read, because it discusses the issues in more detail, although the basic point is that the result depends on the ordering of operations whose ordering is not fully constrained by the standards, and is therefore undefined.

I probably can't reproduce it in full here without also adding a lot of licence information in order to comply with the GFDL. There is a copy at https://gcc.gnu.org/onlinedocs/gcc-3.3.6/gcc/Warning-Options.html

(Take-home message: always compile your code with compiler warnings switched on, but especially if you are seeing possibly unexpected behaviour.)

alani
  • 12,573
  • 2
  • 13
  • 23