Reputation: 41
#define prod(a) (a*a)
using namespace std;
int main()
{
int i = 3, j, k, l;
j = prod(i++);
cout << i << endl;
k = prod(++i);
cout << i << endl;
l = prod(i+1);
cout << i << " " << j << " " << k << " " << l;
}
Why is variable "i
" incremented twice?
i.e to 5 from 3 after j=prod(i++);
Upvotes: 0
Views: 50
Reputation: 409356
Remember that macros are expanded in the source code, not actually called or evaluated.
That means a "call" like
prod(i++)
results in the expanded code
i++*i++
being seen by the compiler.
Many compilers allow you to stop after preprocessing, or otherwise generate preprocessed source, that you can examine to see macro expansions.
If you continue using such a macro with other expressions as arguments, you will soon see another reason they are bad.
Lets say you use
prod(2+4)
Then that will result in the expansion
2+4*2+4
which is equal to
2+(4*2)+4
which is equal to 14, not 36 which might have been expected.
Upvotes: 2
Reputation: 66230
Why is variable "i" incremented twice? i.e to 5 from 3 after j=prod(i++)
Because prod()
is a macro, not a function, so
k=prod(++i);
become
k=(++i * ++i);
Upvotes: 1