gpt4 book ai didi

c++ - 预处理器指令 if-elses 是否正常运行?

转载 作者:太空狗 更新时间:2023-10-29 20:04:18 26 4
gpt4 key购买 nike

来自 How To Write Unmaintainable Code (结构缩进):

One of the most imaginative uses of the preprocessor I have heard of was requiring five passes through CPP before the code was ready to compile. Through clever use of defines and ifdefs, a master of obfuscation can make header files declare different things depending on how many times they are included. This becomes especially interesting when one header is included in another header. Here is a particularly devious example:

#ifndef DONE
#ifdef TWICE
// put stuff here to declare 3rd time around
void g(char* str);
#define DONE
#else // TWICE
#ifdef ONCE
// put stuff here to declare 2nd time around
void g(void* str);
#define TWICE
#else // ONCE
// put stuff here to declare 1st time around
void g(std::string str);
#define ONCE
#endif // ONCE
#endif // TWICE
#endif // DONE

鉴于此代码,我预计会出现以下行为:

  1. 评估#ifndef DONEtrue,进入那个 block
  2. 评估#ifdef TWICEfalse
  3. 跳转至 #else//TWICE
  4. 评估#ifdef ONCEfalse
  5. 跳转至 #else//ONCE
  6. #define ONCE
  7. #endif 三遍

为什么预处理器要进行多次“通过”?预处理器指令中的 if-else 是否表现得不像标准的 if-else 控制结构?在预处理器 if 语句中调用函数是否会导致完全重新评估?

最佳答案

引用你引用的内容:

a master of obfuscation can make header files declare different things depending on how many times they are included

此处的作者假设您多次包含此文件。换句话说,您可能有一个看起来像这样的文件:

#include "that.file.in.your.question.h"
#include "that.file.in.your.question.h"
#include "that.file.in.your.question.h"

第一次,流程如你所描述,导致ONCE被定义。第二次,因为现在定义了 ONCE,所以它采用了不同的分支(定义了 TWICE 的分支)。第三次,因为定义了 TWICE,所以它采用了不同的分支(定义了 DONE 的分支)。最后,第四次,以及此后的任何一次,因为定义了 DONE,所以跳过了整个过程。当然,除非某些其他预处理器指令取消定义 DONE

关于c++ - 预处理器指令 if-elses 是否正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20780924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com