Re: Macros



Harry wrote:
Hi all,Nice Day to you


I have a piece of code as

# define prod(a,b)=a*b
main()
{
int x=2;
int y=3;
printf("%d",prod(x+2,y-10));
}

will the macro be evaluated as (2+2)*(3-10)=4* -7 =-28.

Obviously not, since macro expansion is just text replacement.
[Also obviously not because of the spurious '=' in the macro definition. Please post your real code next time.]
prod(x+2,y-10) is expanded to
x+2 * y-10
which is the same as
x + 2*y - 10 = 2 + 2*3 - 10 = 2 + 6 - 10 = -2


I executed this code,but this o/p is not coming.
What is the reason?

Because you forgot to parenthesize your macro properly. Any basic textbook should have this information (if you bothered to read it). The macro should be
#define prod(a,b) ((a)*(b))
or better, use an inline function:
inline int prod(int a, int b) { return a*b; }

Is it that expressions should not be passed as arguments to macro
functions...

No, but write your macros correctly. The biggest gotcha with expressions is that they may be evaluated more than once, possibly with nasty unforeseen consequences. The prototypical case is
#define prod(a,b) ((a)*(b))
{
int a = 2, b;
/* ... */
b = prod(a++,a++);
/* ... */
}

Please try consulting your elementary textbook at some point in learning C.
.



Relevant Pages