Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program output is confusing

Tags:

c

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

like image 542
John Avatar asked Feb 26 '11 16:02

John


2 Answers

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))
like image 136
CB Bailey Avatar answered Sep 19 '22 22:09

CB Bailey


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))
like image 34
ChrisJ Avatar answered Sep 22 '22 22:09

ChrisJ