How to stringify an expression in C

前端 未结 7 1310
刺人心
刺人心 2020-12-07 01:53

Is there a way to evaluate an expression before stringification in c?

example:

#define stringify(x)  #x
...
const char * thestring = stringify( 10 *          


        
7条回答
  •  囚心锁ツ
    2020-12-07 02:25

    I'll take a wild guess that you have more experience in scripting languages than in C.

    There are multiple phases you have to be aware of with a purely compiled language like C: Preproccesing, Compiling, Linking, and Running

    First the preprocessor is run. That is where your macro gets expanded. At this point, its contents are "10 * 50". Not much to be done about that.

    After the macro pre-processor completes, then the compiler converts the program into an object file

    After the compiler finishes on every source file, the linker steps in and slaps them all together.

    Finally, when your user is ready, they execute your program. Semanticly, this is when the 10 * 50 gets calculated. (In actuality, most compilers will recognize that this will always be the same value, and replace it with 500, but that's an implementation detail).

    Scripting languages like to blur all these lines, so I can see where someone used to one of those might be confused.

提交回复
热议问题