I wonder if I can at the same time assign a value and check if it changed in a C conditional expression without introducing new examples. Consider the function test as fixed in the following example (I don’t want to change its parameters or return values). I search for a variation of the conditional in the main routine which prints "works" because the value of n is incremented by 1 by the test routine. I.e. I want a comparison with the old value of nsing. At the same time it should print "works not" if n would not be incremented by test. I wonder if this could be possible exploiting rules for the order of evaluation or something, i.e. without introducing new variables which store the value of n.
#include <stdlib.h>
#include <stdio.h>
int test(int n)
{
return n + 1;
}
int main()
{
int n;
if ((n = test(n)) == n) {
printf("works not\n");
} else {
printf("works\n");
}
return 0;
}
No, you can’t do that and that’s undefined behaviour, because there’s no sequence point between the assignment and the comparison.