I’m trying to understand the behavior of C code involving multiple increments and usage within the same statement. Consider the following two code snippets:
Code #1:
#include <stdio.h>
void main(){
int a = 10;
printf("%d %d %d", a++, ++a, a); // The output here is // 11 12 12
}
Code #2:
#include <stdio.h>
void main(){
int a = 10;
printf("%d", a++ - ++a - a); // The output here is // 10
}
I’ve read that such operations can lead to undefined behavior, but I’m trying to understand why the output of these snippets might differ.
Could someone please explain the behavior of these code snippets in detail? Specifically, why does the first snippet potentially produce different results on different compilers or even on different runs?
Thank you!
SURIYA PRASATH S is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.