-1

I'm not able to understand, why this code produces this output. Can anyone help me with this??

#include <stdio.h>

int main( void )
{
    int num = 5;

    printf( "%d %d %d", num, ++num, num++ );
}

The output will be 7 7 5 (and NOT 5 6 7)

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • 2
    Please include your code, as code, not an image. Ditto for the output – Alexander Oct 10 '21 at 15:32
  • 2
    You may want to read this: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/12149471) – Andreas Wenzel Oct 10 '21 at 15:33
  • I'd wager this is UB (undefined behavior), since Godbolt outputs `5 6 6` for the same code (and emits warnings). https://godbolt.org/z/bbhd95hP3 – AKX Oct 10 '21 at 15:34
  • 2
    @AKX: You are correct. The behavior is undefined according to [§6.5 ¶2 of the ISO C11 standard](http://port70.net/~nsz/c/c11/n1570.html#6.5p2). – Andreas Wenzel Oct 10 '21 at 15:42
  • If you can understand the output of `printf("%d ", num); printf("%d ", ++num); printf("%d ", num++); printf("%d\n", num);`, you will know just about everything you need to know about how the `++` operator works. – Steve Summit Oct 10 '21 at 17:27

1 Answers1

2
Making side effects happen in the same order as in some other compiler.

It is never safe to depend on the order of evaluation of side effects. For example, a function call like this may very well behave differently from one compiler to another:

void func (int, int);

int i = 2;
func (i++, i++);

There is no guarantee (in either the C or the C++ standard language definitions) that the increments will be evaluated in any particular order. Either increment might happen first. func might get the arguments ‘2, 3’, or it might get ‘3, 2’, or even ‘2, 2’.

https://gcc.gnu.org/onlinedocs/gcc/Non-bugs.html

Alexander
  • 59,041
  • 12
  • 98
  • 151