0

As I know in C, passing of actual parameters of a function evaluation starts from rightmost and directed to left. What is the case for a macro definition with parameter? I made a code to make the sense clear but output confused me... Here is the code.,

#define parsing(a,b) a*b

int parsefun(int a, int b)
{
    return a*b;    
}

int main()
{
    int i=10;
    printf("%d\n",parsing((i++),i));
    i=10;
    printf("%d\n",parsing(i,(i++)));
    i=10;

    printf("%d\n",parsefun((i++),i));
    i=10;
    printf("%d\n",parsefun(i,(i++)));
    system("PAUSE");
    return 0;
}

This code outputs, 100 100 100 110

I hoped same output for macros as function. But where is the crucial point here?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
amin__
  • 1,018
  • 3
  • 15
  • 22
  • 1
    'As I know in C' -- Since you're incorrect, it's worth considering why you thought you knew that, and what else you might think you know that is incorrect. – Jim Balter Jun 24 '12 at 10:59

1 Answers1

7

parsing of actual parameters of a function starts from rightmost and directed to left

I think you mean "evaluation" rather than "parsing". But that's not true, the C standard does not specify an order.

So the behaviour you're getting for the functions is unspecified by the C standard.

I hoped same output for macros as function

Macro arguments are not evaluated, they're simply substituted. So you end up with this:

int i=10;
printf("%d\n", (i++) * i);
i=10;
printf("%d\n", i * (i++));

After which, you're simply seeing undefined behaviour, as explained in this question: Why are these constructs (using ++) undefined behavior?.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • If order is unspecified, then why the two function call above giving different result?? And what value substituting above two macro substitution?? can you please explain... – amin__ Jun 24 '12 at 10:58
  • 3
    @alaminhosain: Because for this particular compiler, function arguments appear to be evaluated from right to left. But another compiler could choose to do left to right. – Oliver Charlesworth Jun 24 '12 at 10:59
  • if you dont mind please give me the link of C standard if you can.. I read from a book that stuff probably pointers in c by kanetker – amin__ Jun 24 '12 at 11:05
  • 1
    @alaminhosain: Sure. See e.g. section 6.5.2.2 paragraph 10 of the C99 standard. – Oliver Charlesworth Jun 24 '12 at 11:07
  • @alaminhosain See www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf (it's essentially the same as C99, but is free) – Jim Balter Jun 24 '12 at 12:32