The Gateway to Computer Science Excellence
+5 votes
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...

in Programming by Boss (31.6k points) | 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

@AskHerOut

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);
	// your code goes here
	return 0;
}

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

0
@Arjun sir,

please see this qsn
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 '--' ??

1 Answer

+6 votes
Best answer

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 by
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,391 answers
198,589 comments
105,442 users