The problem is caused because you're trying to mix information that it is considered at different stages in the processing of the code.
Macros and all CPP (C-Pre-Processor) stuff happens (as its own name indicates) before anything else. It doesn't know anything about the variable values (at most, about #define) and most of what it does is text wrangling.
Some of the variable values might be known at compile time (see constexpr) ... but most of them will only be known at run time.
So, in summary your code fails because the preprocessor knows nothing about the id
variable.
Edit: Explaining the sum example.
We have this code x.cpp
#define sum(a,b) a + b
int main(int argc, char **argv) {
int x = 1, y = 2;
return sum(x,y);
}
And this code compiles and works fine.
Let's look at what happens behind the scenes.
All C/C++ source files are preprocessed. This means that they are evaluated with a different language than either C or C++: the CPP (C-preprocessor). This CPP is the one responsible of all the #... stuff (for example searching and including the header files) and as I said, has nothing to do with C or C++.
In fact, you can even run it without the compiler (try cpp x.cpp
) or you can instruct the compiler to only execute this phase (g++ -o x.i -E x.cpp
)
If we look into x.i:
# 1 "x.cpp"
# 1 ""
# 1 ""
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "" 2
# 1 "x.cpp"
int main(int argc, char **argv) {
int x = 1, y = 2;
return x + y;
}
We can observe several things:
- There's a number of additional '#' lines. Those are used by the compiler to keep track of where everything came from and what was the origin of the included bits, in order to be able to provide meaningful error messages.
- Note how our sum macro has been replaced in the code. This is done blindly and the resulting string turned out to be incorrect C/C++ syntax it will not be detected yet, but only when the actual C/C++ parsing is done.