Use #define preprocessor directive in a weird way
Today I just finish reading and experimenting on C about how to use #define
to create a manifest constant, after that something came into my mind, and below is the code.
#include <stdio.h>
#define dummy main
#define yam {
#define apple }
int dummy(void) //constant substitution main with dummy
yam // constant substitution { with yam
printf("It works!!\n");
return 0;
apple //constant substitution }开发者_如何学运维 with apple
As expected, it works like charm, I just wonder why something like that didn't cause any error, maybe I could understand why the main()
could be substituted because main
is an identifier (name given to a function, variable and constant), but why the {}
can be substituted with a symbolic name too? The second thing is, what data type C use to store this symbolic constant which is not a character enclosed in single quote ""
nor an integer or floating-point number.
The #define
statements are evaluated by a preprocessor before the program is actually compiled, so the compiler never sees yam
. The preprocessor performs a direct text substitution.
That is to say, when the compiler sees your code, it looks like this:
int main(void) //constant substitution main with dummy
{ // constant substitution { with yam
printf("It works!!\n");
return 0;
} //constant substitution } with apple
Define is literally text replacement. In the preprocessor steps, the compiler will go through your code and replace all dummy
with main
, yam
with {
, and apple
with }
.
This works because the preprocessor is a *PRE*processor, i.e. it's something that happens before the real processing.
So the preprocessor does its crude text substitution stuff before the real compiler gets to look at the code.
#define
is handled by the preprocessor. The stuff will be replaced character by character before the compiler compiles the code. You're essentially able to obscure your whole code using #define
but anyone with a precompiler can unobscure it later on. The preprocessor replaces all occurances of the "constant" you defined, except when it's enclosed in quotes (e.g. char *test="dumy yam apple";
will stay unchanged).
精彩评论