testing some code when studying C language,
#include <stdio.h>
#include <math.h>
#define hypotenusa(x, y) sqrt((x) * (x) + (y) * (y))
int main(void) {
int a, x;
x = 2;
a = hypotenusa(++x, ++x);
printf("%d\n", a);
}
And I am getting the answer
6
in one program(dosbox gcc compiler)7
in codelight gcc compiler and8
on codeChef online compiler
can anyone explain this behaviour?
my logic says it should be 6
(sqrt(42)
) but...
It's undefined behaviour.
After the macro replacement
becomes:
As you can see
x
is modified multiple times without any intervening sequence point(s). See What Every C Programmer Should Know About Undefined Behavior.