-1

I tried running this program :

#include<stdio.h>
int main(){
        int a=5;
        printf("%d %d", ++a,a++);
        return 0;
}

with gcc in arch-chroot on a armv7 device. I expect to get output 7 5 but i'm getting 7 6. Can anyone explain what's going on?running the program

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Abinash Dash
  • 167
  • 1
  • 9

2 Answers2

3

Your code is invoking Undefined Behavior (UB)!

Use the warning flgas -Wall -Wextra during compilation, and the compiler will tell you the story:

prog.c: In function 'main':
prog.c:4:30: warning: operation on 'a' may be undefined [-Wsequence-point]
    4 |         printf("%d %d", ++a,a++);
      |                             ~^~
7 5

In that online demo, I got a different output, a characteristic of UB.

Read more in printf and ++ operator.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

6.5p2

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)

++a and a++ are unsequenced. Your program is ill-formed.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142