168 views
#include <stdio.h>
#define A -B
#define B -C
#define C 5
int main(void)
{
printf("%d",A);
return 0;
}


now my doubt here is, before compilaion i think macro will make printf part as,                                                                    printf("%d",--5); which should give L-value error at compile time but,

actually what it is doing is printf("%d",-(-5)); leading to no compiler error and giving answer as 5, but macro implicitly never put precedence braces() itself...

| 168 views
0

Well I am not aware of the internal mechanism C compiler uses to evaluate such mechanism if it doesn't assume parenthesis( I think considers the order of execution as if it would be if there were parenthesis, the following code further validates the assertion being made).

#include <stdio.h>
#define A B+
#define C -D
#define B 10
#define D 5
int main(void)
{
printf("%d", A+C);//Gives No Error & prints 5
return 0;
}

0

i agree with you, but i need to know what is happening there..

if i write code like this,

#include <stdio.h>
#define A 5+10
#define B 10+2
int main(void) {
printf("%d",A*B);
return 0;
}

printf part will look like printf("%d", 5+10*10+2), not like printf("%d",(5+10)*(10+2))...

0
@Arjun sir,

0
- - 5 is error? Macro expansion happens after lexical analysis or before it?
0
before lexical analysis.
0
@Anu Then macro will get replaced even inside comments? Also, how is macro getting the "strings" which are to be substituted -- does it scan word by word and do substitution?
0
And while substituting does it introduce white space after substitution?
0
it is not --5

it is -(-5)

which is +5
0
it is not "--" but "- -".
+1
ok , so it will be  - - 5

and - will evaluates right to left as unary operator

That is why it prints 5 only
0
if you write so without using macro it gives error.
0
@Arjun sir, how it is '- -' instead of '--' ??

Let us make a simpler code version doing almost the same: (to avoid stdio.h which includes a lot of macros)

#define A -B
#define B -C
#define C 5
int main(void)
{
int a = A;
return 0;
}

Now, let us see the result after macro expansion

[email protected]:~\$ gcc -E macro.c
# 1 "macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "macro.c"

int main(void)
{
int a = - -5;
return 0;
}


Hope that explains it -- after macro expansion, preprocessor inserts white space and thus prevent any addition of tokens being created.

by Veteran (432k points)
selected