Re: Macros




Harry wrote:
Hi all,Nice Day to you


I have a piece of code as

# define prod(a,b)=a*b

Macro definitions do not use the '=' operator; in this case, it will
cause a syntax error when the macro is expanded. You want to rewrite
this 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.

As you have written it, the macro will expand to =x+2*y-10, which will
result in a syntax error. Even if you didn't have the extraneous '='
in the expansion, you'll get bitten by precedence rules, since x+2*y-10
evaluates as x+(2*y)-10. That's why you should define the macro as

#define prod(a,b) (a)*(b)

Written this way, prod(x+2,y-10) will expand to (x+2)*(y-10), which is
what you want.


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


You don't have a newline in your format string, so the output isn't
being flushed immediately. Either add the newline to the format
string, or add an fflush() statement after the printf:

printf("%d\n", prod(x+2,y-10));

or

printf("%d", prod(x+2,y-10));
fflush(stdout);

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


You can, you just need to put parens around each argument to avoid
precedence issues.

You do need to be careful if the expression involves side effects (such
as using the autoincrement or autodecrement operator); for example, if
you have the macro definition

#define square(x) (x)*(x)

and you call it as

y = square(a++);

you'll invoke undefined behavior.
can anyone help me out...

thanks in advance.

.