Re: Macros



In article <1164698162.284936.137360@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
Harry <gehariprasath@xxxxxxxxx> wrote:

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.

No, each dummy argument will be *textually* dropped into place exactly
as specified. Thus, your line would expand to

printf("%d",x+2*y-10);

This is why you very often see () in macros, such as

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


Some comments:

- don't use = in the macro definition
- remember to include stdio.h
- look in the FAQ for information about why you want to use a different
way of declaring main
- try adding a \n after the %d or else you might not get -any- output
- notice that when I defined prod(a,b) I enclosed the (a)*(b) in ().
That's because whatever is textually right next to prod(a,b) might happen
to have a higher compilation priority.
- return a value from main. You omitted the 'int' qualifier of
return type, which is not legal in C99, so you cannot take advantage
of the C99 requirement that not returning anything be equivilent
to returning 0; hence you must return something yourself.
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
.



Relevant Pages

  • Re: Macro var args
    ... >> parenthesis in the macro definition. ... > For some reason, i have compiler errors in my real project, while the ... 11 void doThrow(const char * file, int line) ...
    (comp.lang.cpp)
  • Re: Storage space of #defines
    ... > what will it be stored as ie short, int, unisigned int? ... the situation is the same as if the expansion was there all along. ... In other words, given your macro definition above, CLIENT_MSG_HELLO is ... These are general rules, because they are in fact defined by the ...
    (comp.lang.c)
  • Re: Storage space of #defines
    ... > what will it be stored as ie short, int, unisigned int? ... the situation is the same as if the expansion was there all along. ... In other words, given your macro definition above, CLIENT_MSG_HELLO is ... These are general rules, because they are in fact defined by the ...
    (comp.unix.programmer)
  • Re: [PATCH] Reset file->f_op in snd_card_file_remove(). Take 2
    ... The problem is that we use kmalloc for allocating a dummy f_op. ... int err = 0; ...
    (Linux-Kernel)
  • Re: [PATCH] Reset file->f_op in snd_card_file_remove(). Take 2
    ... The problem is that we use kmalloc for allocating a dummy f_op. ... int err = 0; ...
    (Linux-Kernel)