C preprocessor - label insertion - confusing result. Why is this?

I thought this program would print the value -12--2=-10

. When I run it, it prints 0

.

I can't 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;
}

      

+3


source to share


5 answers


The preprocessing phase is performed before any compilation and is executed on the text. It has no concept of variables or types (i.e. compilation phases), let alone actual values ​​(runtime).

So what do you do:



1) ALPHA(i, i2)
2) i##2-i2
3) i2-i2

      

So, you get printf("%d", i2-i2)

that which prints zero.

+7


source


The preprocessor outputs this as:

#include <stdio.h> 

int main(void) {
    int i = -1;
    int i2 = -2;
    printf("%d", i2-i2);
    return 0;
}

      



So it will print null

+6


source


ALPHA(i, i2)

becomes i2-i2

In the above comment, preprocessing is textual replacement BEFORE compiling.

+5


source


The compilation process is slightly different from C compared to other programming languages. In C, 3 steps are involved in getting the .exe file from the .src file.

β†’ xyz.c Preprocessor β†’ tmp.c (temporary) β†’ COMPILER β†’ xyz.obj-> LINKER β†’ xyz.exe

Basically, the preprocessor reads your code line by line, and if it is a preprocessing instruction, then it only executes the preprocessing directive and outputs your code to the compiler in pure text form.

In the case of your code, the 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 to the press as 0 . This is the reason why you get 0 when you run the code. Hope it helps you.

+5


source


You have confused the symbols i

and 1

. Try using a different text editor font.

i ## 2

creates i2

which turns out to be valid in your program with a value -2

.

1 ## 2

needed to get the expected 12

.

This leaves out the negative sign, which you seem to expect, but I still like this theory.

+2


source







All Articles