Search code examples
cmacrosc-preprocessoroperator-precedence

Passing parameters evaluation direction in macro


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?


Solution

  • 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?.