6
#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?

4
  • 5
    Schoolbook example of where C macros go wrong :) Use functions instead. Commented Feb 26, 2011 at 16:54
  • 4
    Isn't this the first thing they warn about in any C programming book? Whatever you use, I'm sure you can find a better one. Commented Feb 26, 2011 at 16:55
  • 4
    Urgh, a void main()... Commented Feb 26, 2011 at 17:22
  • "In my opinion" ... opinions aren't relevant, language standards are. Commented Feb 27, 2011 at 3:44

7 Answers 7

21

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))
Sign up to request clarification or add additional context in comments.

Comments

5

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))

Comments

5

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

k = p+1*p+1

Which of course means you have:

k = 3+1*3+1 = 7

Comments

2
#define PROD(x) (x*x)

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

Comments

2

macro are not function . These are replaced by name

It will be p+1*p+1

Comments

2

This is what compiler is going to see after preprocessors does its job: k= p+1*p+1. When p = 3, this is evaluated as k = 3+(1*3)+1. Hence 7.

Comments

1

This is exactly why you should use functions instead of macros. A function only evaluates each parameter once. Why not try

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

and see the difference!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.