0

If x and y are pointers to the same variable variable, what does *x++=*y++ mean?

int a,*x,*y;
*x++=*y++;

I expected an error but it didn't

  • 1
    ***If*** `*x` and `*y` point to the same variable then `*x = *y` has no effect. But `*x++ = *y++` increments both pointers afterwards. – Weather Vane Aug 27 '17 at 13:26
  • 4
    This question lacks a [mcve] ... from the code shown, `x` and `y` are uninitialized. –  Aug 27 '17 at 13:26
  • Possible duplicate of [Confusing answers : One says \*myptr++ increments pointer first,other says \*p++ dereferences old pointer value](https://stackoverflow.com/questions/16281872/confusing-answers-one-says-myptr-increments-pointer-first-other-says-p-d) – anatolyg Aug 27 '17 at 14:07
  • It is undefined behaviour. – msc Aug 27 '17 at 14:20
  • @rsp probably not, as by the text ... but yes, **only** the code lines shown here would be undefined. –  Aug 27 '17 at 14:26
  • You _could_ get an error because in your example x and y have not been initialized. Should they point to memory outrside your assigned memory, you get a segmentation fault. Or you get an error (or seg fault) if this has changed another variable the program relies on. Or...this is so-called _undefined behavior_ because now anything can happen. – Paul Ogilvie Aug 27 '17 at 16:46

1 Answers1

4

This expression is similar to

*x = *y;
x++;
y++;

The operators you see in *x++ = *y++ will be evaluated with regard to the C operator precedence rules. The increment ++ operator has a higher precedence than the dereference *, but since we have a post-increment the operations will be carried out after the assignment.

yacc
  • 2,915
  • 4
  • 19
  • 33
  • Is it about the priority of the operators? – Hiruni Nimanthi Aug 27 '17 at 13:47
  • 1
    @HiruniNimanthi I added an explanation regarding the precedence evaluation. – yacc Aug 27 '17 at 14:18
  • 1
    Note there's no such thing as *operator precedence* in C. There's only a grammar that allows to deduce a precedence order, but with some limitations. Apart from that, correct, `*x++` is equivalent to `*(x++)`. –  Aug 27 '17 at 14:21