0

I am running gcc 7.4.0 on ubuntu 18.04. I compiled and ran the following code

#include<stdio.h>

int main() {
  int *p;
  int a[2];
  a[0] = 100;
  a[1] = 200;
  p = a;
  int b = 10;
  printf("%d\t%d", ++*p, *p);
  printf("\n%d\n", *p);

  printf("%d\t%d", ++b, b);
  printf("\n%d\n", b);
  return 0;
}

I am getting this output:

101     100
101
11      11
11

Why is the pre-increment operator behaving differently with the integer value pointed by pointer and the ordinary integer value?

Bukks
  • 408
  • 7
  • 16
  • 1
    You've entered into territory of undefined behavior with `printf("%d\t%d", ++*p, *p);`. Your compiler should throw sequence point warnings for this code. See https://stackoverflow.com/a/34536741/5291015 – Inian Nov 15 '19 at 04:41
  • (as well as *conversion specifier* warnings for attempting to print pointers with `"%d"`...) – David C. Rankin Nov 15 '19 at 05:24

1 Answers1

0

See this warning. It is a undefined behaviour. it means anything can happens.

prog.cc: In function 'int main()':
prog.cc:10:20: warning: operation on '* p' may be undefined [-Wsequence-point]
   10 |   printf("%d\t%d", ++*p, *p);
      |                    ^~~~
prog.cc:13:20: warning: operation on 'b' may be undefined [-Wsequence-point]
   13 |   printf("%d\t%d", ++b, b);
      |                    ^~~
prog.cc:13:20: warning: operation on 'b' may be undefined [-Wsequence-point]

You should compile your program with -pedantic option.

msc
  • 33,420
  • 29
  • 119
  • 214