-2

My question is regarding assigning a variable to it's post-incremented value. This was undefined in previous versions of C as pointed out in this question but it's defined in C17.

I've followed this StackOverflow post regarding post-incrementing variables in C. So, if we have the following code snippet -

int a = 1;
int b = a++;
printf("%d\n", b);

The variable b gets assigned the initial value of a (i.e. 1) before a gets incremented. Hence, the output is 1, as expected.

But, what if we assign a to it's post-incremented value?

int a = 1;
a = a++;
printf("%d\n", a);

Similar to the above case, a first gets assigned the original value (1), but shouldn't the incremented value get printed as the final output?

nobis
  • 1
  • 2
  • 3
    I don't know if it has been changed in later standards, but traditionally `a = a++` used to be *undefined behavior*. There's no sequencing between the assignment and the increment. – Some programmer dude Aug 21 '23 at 04:25
  • 3
    **If** this becomes defined in the future, I hope that it will be required to print `1`. – Ted Lyngmo Aug 21 '23 at 04:33
  • @TedLyngmo I'm running C17 and it does output 1. – nobis Aug 21 '23 at 09:00
  • @nobis Yes, but it's not required to do so since it has undefined or unspecified behavior. – Ted Lyngmo Aug 21 '23 at 09:06
  • @nobis I see that you now added _"it's defined in C17"_. That would surprise me. Where did you find that information? – Ted Lyngmo Aug 21 '23 at 09:15
  • @nobis C17 is a language standard that lays out how valid C programs look like and how they should behave. It's not a tool, you can't be "running" C17. The C17 standard does not mandate what happens in this case. You can't rely on any behaviour you're seeing because this code is _invalid_ C. Asking about why this code has any particular behaviour is like asking "why" you can get certain solutions in equations if you just assume you can divide by 0; You can't divide by 0, anything you did after making that assumption is meaningless. – Cubic Aug 21 '23 at 09:37
  • @nobis: Re “I'm running C17”: It is impossible to run C17 because C17 is not a programming language. C17 is a specification of the minimum requirements for a programming language. Many implementations of that specification are possible. You used one implementation of that programming language (and likely an imperfect implementation). The behavior you observed tells you about features of that implementation, not of the C standard generally. – Eric Postpischil Aug 21 '23 at 10:56

0 Answers0