John
John

Reputation: 151

C program output 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 anyone please tell me why?

Upvotes: 6

Views: 534

Answers (7)

Bo Persson
Bo Persson

Reputation: 92261

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!

Upvotes: 1

Raghav Navada
Raghav Navada

Reputation: 317

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.

Upvotes: 2

Vivek Goel
Vivek Goel

Reputation: 24140

macro are not function . These are replaced by name

It will be p+1*p+1

Upvotes: 2

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

#define PROD(x) (x*x)

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

Upvotes: 2

ChrisJ
ChrisJ

Reputation: 5251

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

Upvotes: 5

murrekatt
murrekatt

Reputation: 6129

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

Upvotes: 5

CB Bailey
CB Bailey

Reputation: 791759

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

Upvotes: 21

Related Questions