Comma operator can be used sometimes to inject side effects into expressions:
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int max = 10; double x = 0; while (max--, printf("%d\n", max), max) { /* sth */ } x = printf("x: %f", x), x = sqrt(x), printf(", sqrt(x): %f\n", x), x; return EXIT_SUCCESS; }
bash-3.2$ gcc -strict -pedantic -Wall main.c && ./a.out 9 8 7 6 5 4 3 2 1 0 x: 0.000000, sqrt(x): 3.316625It's discouraged, for example by MISRA C
Debugging this would be an exciting experience ;) I like those tricks, please keep posting them ;)
ReplyDeleteThanks!
Delete