【发布时间】:2017-05-27 05:35:46
【问题描述】:
由于某种原因,我在文档的任何地方都没有找到这个问题的直接答案。
我的朋友说我可以直接使用__func__ 并分配给它,而无需实际声明它。
1. The identifier __func__ shall be implicitly declared by the translator as
if, immediately following the opening brace of each function definition, the
declaration
static const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function.
那么,这是否意味着,每次我以static const char __func__[] = "function-name"; 而不是strcpy(__func__, "function-name"); 开始函数时,我都应该声明它,因为它已经被声明并将由编译器处理?
如果这听起来像一个基本问题,我很抱歉,但我很困惑!
【问题讨论】:
-
好吧,你不能给它赋值,因为它是一个 const 数组......
-
文档提到了分配字符串的 translator。你为什么假设自己是翻译者?
-
是的,当我现在阅读它时,我意识到我听起来多么愚蠢。
-
否;你没有声明它——它是由翻译器隐式声明的(意思是“编译器”)。不;你不能修改它——它被声明为
const。有趣的是,GCC 和 Clang 都不允许你在函数的内部块中重新定义__func__,但它给出的错误不是很连贯(error: expected identifier or ‘(’ before ‘__func__’,但将__func__更改为__function__并且代码编译)。 OTOH,无论如何,您都不应该尝试这种技巧。 -
@JonathanLeffler 可能 gcc 以某种方式将
__func__替换为字符串文字,而不是声明的变量。如果您编写int __func__;,您将得到与编写int "hello";时相同的编译器错误。不过,这个字符串文字似乎具有const char*类型,而不是像常规字符串文字那样的char*。
标签: c char constants variable-assignment