#include<stdio.h>
#include<conio.h>
#define PROD(x) (x*x)
void main()
{
clrscr();
int p=3,k;
k=PROD(p+1); //here i think value 3+1=4 would be passed to macro
printf("\n%d",k);
getch();
}
In my opinion, the output should be 16
, but I get 7
.
Can anyone please tell me why?
Macros are expanded, they don't have values passed to them. Have look what your macro expands to in the statement that assigns to k
.
k=(p+1*p+1);
Prefer functions to macros, if you have to use a macro the minimum you should do is to fully parenthesise the parameters. Note that even this has potential surprises if users use it with expressions that have side effects.
#define PROD(x) ((x)*(x))
The preprocessor expands PROD(p+1) as follows:
k = (p+1*p+1);
With p=3, this gives: 3+1*3+1 = 7.
You should have written your #define as follows:
#define PROD(x) ((x)*(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With