简体   繁体   English

宏解析地址

[英]Macro resolution address

#define PLAINTEXT_TARGET "plaintext"
if( strstr(PLAINTEXT_TARGET, optarg) == PLAINTEXT_TARGET )
    /* ... */

Does the C language guarantee that PLAINTEXT_TARGET above compiles into a single instance? C语言是否保证上面的PLAINTEXT_TARGET可以编译为单个实例? If the compiler may produce two instances of the macro string then the conditional above is misleading and can be false. 如果编译器可能产生宏字符串的两个实例,则上述条件会产生误导,并且可能为假。

Macros do simple textual replacement. 宏进行简单的文本替换。 The preprocessor replaces every occurrence of PLAINTEXT_TARGET with "plaintext" , after that the compiler looks at the result and compiles that. 预处理器将每次出现的PLAINTEXT_TARGET替换为"plaintext" ,然后编译器查看结果并将其编译。

So the compiler sees two string literals and it's not guaranteed that those won't be stored separately (see Alok's answer for the according quote from the standard). 因此,编译器会看到两个字符串文字,并且不能保证不会将它们分开存储(有关标准中的相应引用,请参阅Alok的回答)。 The code is indeed misleading, it would be more reasonable to declare PLAINTEXT_TARGET as a constant: 该代码确实具有误导性,将PLAINTEXT_TARGET声明为常量会更合理:

const char* const PLAINTEXT_TARGET = "plaintext";

No, it is not guaranteed by the standard. 不,该标准不能保证。 The standard says this about "string literals" (6.4.5p6): 该标准对“字符串文字”(6.4.5p6)进行了说明:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. 如果它们的元素具有适当的值,则不确定这些数组是否不同。

These arrays refers to the array of char created from a literal string in translation phase 7. 这些数组引用在转换阶段7中从文字字符串创建的char数组。

Since you are using a macro, the code seen by the compiler is: 由于您使用的是宏,因此编译器看到的代码是:

if( strstr("plaintext", optarg) == "plaintext" )

When optarg is "plaintext" , the code reduces to optarg"plaintext" ,代码减少为

if("plaintext" == "plaintext")

As mentioned above, this is not guaranteed to be true in C. 如上所述,不能保证在C中是正确的。

So, you must use strcmp() instead of checking the pointers for equality, or, as in the other answer, define a char * pointer to use instead of the macro. 因此,您必须使用strcmp()而不是检查指针是否相等,或者,如在其他答案中一样,定义要使用的char *指针而不是宏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM