Could you please explain why the below program's result is different?
Program :
#define MUL(X) X*X
int main()
{
int i=3;
cout<<MUL(++i)<<"\n";
return 0;
}
Output :
25
Could you please explain why the below program's result is different?
Program :
#define MUL(X) X*X
int main()
{
int i=3;
cout<<MUL(++i)<<"\n";
return 0;
}
Output :
25
In order to analyse this, let's expand the macro, which becomes ++i * ++i
.
Formally, the behaviour of ++i * ++i
is undefined as *
is not a sequencing point, and ++
mutates the i
. So the compiler can do anything, and no further explanation is necessary.
If your compiler supports typeof
(which is compile-time evaluable so will not do any incrementing), and expression statements, then the safe version of your macro is
#define MUL(i) ({ \
typeof(i) j = (i); \
j*j; \
})
although it would be wise to avoid a macro altogether and use a function.