Pin C is confusing

#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 someone tell me why?

+6
c
source share
7 answers

The preprocessor extends PROD (p + 1) as follows:

 k = (p+1*p+1); 

For p = 3 this gives: 3 + 1 * 3 + 1 = 7.

You should write your #define as follows:

 #define PROD(x) ((x)*(x)) 
+5
source share

Macros are extended; they have no values ​​passed to them. See that your macro expands in an instruction that assigns k .

 k=(p+1*p+1); 

Prefer functions for macros, if you need to use a macro you have to do is copy the parameters completely. Note that even this one has potential surprises if users use it with expressions that have side effects.

 #define PROD(x) ((x)*(x)) 
+21
source share

The problem is that PROD is a macro and will not behave exactly as you intend it. Therefore, it will look like this:

 k = p+1*p+1 

Which, of course, means:

 k = 3+1*3+1 = 7 
+5
source share
 #define PROD(x) (x*x) 

PROD(3+1) changed by the preprocessor to 3+1*3+1

+2
source share
Macro

not functioning. They are replaced by the name

It will be p+1*p+1

+2
source share

This is what the compiler sees after the preprocessors complete their work: k = p + 1 * p + 1. At p = 3, this is estimated as k = 3+ (1 * 3) +1. Therefore 7

+2
source share

That is why you should use functions instead of macros. The function evaluates each parameter only once. Why not try

int prod (int x)
{return x * x; }

and see the difference!

+1
source share

All Articles