user3126632
user3126632

Reputation: 467

Why macro and function having same name works only when macro is defined after function defintion?

The below code works fine

void a()
{
    printf("In fn");
}

#define a() printf("In macro")

void main()
{
    a();
}

O/p In macro

But look at this code when macro is defined before the funcn definition.(Throws compilation error)

#define a() printf("In macro")

void a()
{
    printf("In fn");
}


void main()
{
    a();
}

My question why it does work when macro definition is after function declaration and doesn't work when it is before it....

Upvotes: 0

Views: 94

Answers (1)

2501
2501

Reputation: 25753

In the first case the result is:

void a()
{
    printf("In fn");
}

void main()
{
    printf("In macro");
}

And in the second:

void printf("In macro")
{
    printf("In fn");
}

void main()
{
    printf("In macro");
}

Which is obviously not c code.

Defines are replaced before compilaton.

Upvotes: 3

Related Questions