please help to solve this c program based on MACROS

Ashokkumar01cbe

Broken In
include"stdio.h"
#define prod(x) (x*x)
void main()
{
int i=3,j,k,l;
j=prod(i+1);
k=prod(i++);
l=prod(++i);
printf("%d\n%d\n%d",j,k,l);
}
i got the output in gcc compiler as 7,9,and 49
please explain me how the output will be like this..
 

Desmond

Destroy Erase Improve
Staff member
Admin
We already have a thread to post such questions here : *www.thinkdigit.com/forum/programming/132924-c-c-beginners-guide-post-basic-questions-here.html, but anyway :

Keep in mind that Macros are basically nothing but string substitution.

In the first case, j=prod(i+1) gets replaced by (i+1*i+1). Since * has a higher precedence than +, therefore, 1*i is evaluated first, which results in 3. Consequently, 3+3+1 = 7.

In the second case, we get (i++*i++). Being post increment, the "i" is used first and then incremented. So, resulting in 3*3 = 9. After this it will increment two times because increment is called two times. So, "i" is now 5.

In the third case, (++i*++i), there are pre-increment operators. Since i=5, owing to previous increments, again incrementing two times, "i" is now 7. Therefore, operating as usual, 7*7 = 49.

You're welcome.
 
Last edited:

nbaztec

Master KOD3R
You're defining the macros wrong.

A common pitfall while defining macros is when the programmer fails to properly parenthesize the arguments:
Code:
#define prod(x) (x)*(x)

The repercussions of which are explained by Desmond.
 
Top Bottom