Reputation: 11174
I thought this program would print the value -12--2=-10
. When I run it, it prints 0
.
I cannot figure out why? Any hints?
#include <stdio.h>
#define ALPHA(x,y) x##2-y
int main(void) {
int i = -1;
int i2 = -2;
printf("%d", ALPHA(i, i2));
return 0;
}
Upvotes: 3
Views: 226
Reputation: 1250
Compilation process is a bit different in C as compared to other programming languages. In C, 3 phases are involved in getting an .exe file from .src file.
xyz.c -> PREPROCESSOR -> tmp.c(temporary) -> COMPILER -> xyz.obj-> LINKER -> xyz.exe
Basically, a preprocessor reads your code line by line and if it is a preprocessing statement, then only it performs the preprocessing directive and outputs your code to the Compiler in pure textual form.
In case of your code,preprocessor will send this code to the compiler for compilation :
//includes stdio.h from include folder
int main(void)
{
int i = -1;
int i2 = -2;
printf("%d", i2 - i2);
return 0;
}
So,when the compiler will compile this code,it will give the result for print as 0 only. This is the reason you are getting 0 printed, when you are running the code. Hope this will help you.
Upvotes: 6
Reputation: 137930
You mixed up the i
and 1
characters. Try a different text editor font.
i ## 2
produces i2
which happens to be valid in your program, with a value of -2
.
1 ## 2
is needed to get the expected 12
.
That doesn't account for the negative sign you seem to expect, but I still like this theory.
Upvotes: 2
Reputation: 38128
The preprocessor will output that as:
#include <stdio.h>
int main(void) {
int i = -1;
int i2 = -2;
printf("%d", i2-i2);
return 0;
}
So it will print zero
Upvotes: 6
Reputation: 2902
The preprocessing phase is done before any compilation and is done on text. It has no notion of variables or types (that is the compile phase), let alone actual values (runtime).
So, what you are doing is:
1) ALPHA(i, i2)
2) i##2-i2
3) i2-i2
So you end up with printf("%d", i2-i2)
which prints zero.
Upvotes: 7
Reputation: 12044
ALPHA(i, i2)
becomes i2-i2
Per a comment above, pre-processing is textual replacement BEFORE compilation happens.
Upvotes: 5