nikola
nikola

Reputation: 125

Macro output explanation

Can someone explain the output of this program -

#include<stdio.h>
#include<conio.h> 

#define FUDGE(k) k+3.14159
#define PR(a) printf(#a" = %d\t ",(int)(a))
#define PRINT(a) PR(a);putchar('\n')

int main()
{
    int x=2;

    PRINT(x*FUDGE(2));
    printf(\n);
    PR(x*FUDGE(2));

    return 0;
}

OUTPUT -

x*2+3.14159 = 7

x*FUDGE(2) = 7

Why is FUDGE(2) getting printed in second and not in the first statement.

Upvotes: 3

Views: 102

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

Because in the first you use PRINT which expands the argument when it "calls" PR.

Upvotes: 1

ugoren
ugoren

Reputation: 16441

The # operator is strange. It works before expanding the parameter.

So when calling PR(x*FUDGE(2)), # is applied to x*FUDGE(2) before FUDGE is expanded.
However, in PRINT(x*FUDGE(2)), FUDGE is expanded before passing it on to PR. When PR applies # to it, it has already been expanded.

Upvotes: 6

Related Questions