0

What does the forth line do?

int i = 0;

int a[3] = {0, 1, 2};

int *p = a;

*p++ = *p++; /* this line here */

Just for completeness, this is the output:

printf("a = %p, p = %p\n", a, p); /* a = 000000000061FE30, p = 000000000061FE34 */

for(i = 0; i < 3; i++)
    printf("a[%d] = %d%s", i, a[i], (i<2)? ", ": "\n"); /* a[0] = 1, a[1] = 1, a[2] = 2 */
  • 3
    Undefined behavior. – EOF May 13 '17 at 12:11
  • It's **Undefined Behaviour**. Anything can happen. The compiler may reject the program, the program (if available) may do nothing, it may shift the values in the array, it may transfer money from your bank account to mine, ... – pmg May 13 '17 at 12:12
  • but why the down vote? – Maykel Jakson May 13 '17 at 12:13
  • @EOF this is a c code not a c++ – Maykel Jakson May 13 '17 at 12:15
  • @MaykelJakson The rules are the same in this case. Also, the duplicate question is about C as well. – EOF May 13 '17 at 12:16
  • @EOF is this line of code: `*q++ = *q++ + 1` has undefined behavior too? – Maykel Jakson May 13 '17 at 12:19
  • @MaykelJakson Why wouldn't it? – EOF May 13 '17 at 12:22
  • @EOF Which question is this a duplicate of? – Sush May 13 '17 at 12:26
  • @EOF alright, thanks – Maykel Jakson May 13 '17 at 12:26
  • 1
    @Sush [this](http://stackoverflow.com/q/949433/3185968) – EOF May 13 '17 at 12:27
  • It doesn't matter what it's a dupe of - it's appalling bad code that should never be used. It's a terrible example and of negative use to future visitors:( The answer to 'What does the forth line do?' is 'gets you fired' or 'gets you an F- mark'. – ThingyWotsit May 13 '17 at 12:32
  • @ThingyWotsit this code is not to be used for productive purposes of course, it just a try to understand pointers, and I didn't heard of **Undefined Behavior** before. I was trying to see the difference between `*p++ += 1` and `*p++ = *p++ + 1`, I spent a whole day trying to understand why `*p++ = *p++ + 1` didn't work the way I expected, because I didn't know about the concept of **Undefined Behavior**. – Maykel Jakson May 13 '17 at 12:38
  • @MaykelJakson-- The particular problem in your question has to do with sequence points and the way that expressions are evaluated in C; this is a well-known issue. C is filled with such pitfalls; UB comes in many forms. Get a good book to learn from, as C is not a good language to learn by trial and error. Reading questions on SO is also a good way to familiarize yourself with these subtleties; this exact question comes up here often (several times each week?). So often in fact, that the [tag wiki](http://stackoverflow.com/tags/c/info) specifically asks that you avoid this question. – ad absurdum May 13 '17 at 13:58
  • @DavidBowling a good book like what? – Maykel Jakson May 13 '17 at 15:11
  • 1
    [Here is a post filled with book recommendations](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – ad absurdum May 13 '17 at 15:15

0 Answers0