Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is *pt +++= 20 valid?

The following was an exam question. +++= looked bizarre, so I asked MS Copilot and it kept saying that it’s invalid, and Google Gemini said it may work but it’s undefined. Is *pt +++= 20; valid and is guaranteed to be the same as *pt++ += 20;

#include <stdio.h>
void main()
{
    int num[4] = {1, 2, 3, 4};
    int *pt = num;
    pt++;
    *pt++ = 5;
    *pt ++= 10;
    pt--;
    *pt +++= 20;
    printf("%d %d %d %d", num[0], num[1], num[2], num[3]);
}

The answer of the exam was "1 5 30 4" and it was the case when I ran the code on my computer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This evil-looking (bad) exam question is actually valid and well-defined.

  • *pt = num; point at first item, OK.
  • pt++; point at second item, OK.
  • *pt++ = 5; de-reference second item (and write 5 there), then point at third item, OK.
  • *pt ++= 10; de-reference third item (and write 10 there), then point at fourth item, OK.
  • pt--; back to third item.
  • *pt +++= 20; de-reference third item (and add 20 there), then point at fourth item, OK.

*pt +++= 20; specifically is parsed according to something that’s informally called "the maximal munch rule" (more info here), meaning that the C parser will look for the longest sequence that forms a valid token, then use that.

In this case ++ is a longer valid sequence than +, so this will always get treated like (*pt++) += and not as (*pt + ) ++=.

Operator precedence from there: postfix ++ highest, over unary *, over += compound assignment. The pointer increment will naturally happen at the end of the expression, like in all the other cases here. Now as it happens, the result of * is a so-called "lvalue", a modifiable memory location, so we can use += on top of that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading