在下面的代码中,函数test
和test2
是等价的吗?
typedef int rofl;
void test(void) {
rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}
void test2(void) {
rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}
换句话说:
sizeof(rofl)
中的rofl
是否因为括号正确选择了rofl
type?<sizeof *rofl
中的rofl
是否正确选择了rofl
变量 因为缺少 的括号?
注意:这是一个看起来很傻的例子,但在实践中实际上可能会发生类型名称与变量名称相同的情况。因此问题。
最佳答案
在这两种情况下,最后的rofl
都是变量名。变量名一出现就在范围内;对于当前范围的其余部分,普通上下文中的标识符 (*) 始终表示变量名。
sizeof
运算符不会为名称查找引入任何特殊情况。事实上,没有语言结构会使用标识符的隐藏含义。
在实践中,最好不要对类型和变量名称使用相同的标识符。
(*) 标识符有三种特殊上下文:标签名称、结构标记和结构成员。但在所有其他上下文中,所有标识符共享一个公共(public) namespace :类型名称、变量名称、函数名称等没有不同的标识符 namespace 。
这是一个人为的例子:
typedef int A; // "A" declared as ordinary identifier, meaning a type name
struct A { A A; }; // "A" declared as struct tag and member name -- OK as these are three different name spaces. Member type is "int"
A main() // int main() - ordinary context
{
struct A A(); // "A" declared as ordinary identifier, meaning a function name; hides line 1's A
// A C; // Would be error: ordinary A is a function now, not a typedef for int
struct A B; // OK, struct tags have separate name space
A:+A().A; // OK, labels and struct members have separate name space, calls function
goto A; // OK, label name space
}
关于c - 在这种情况下,C 是否正确处理了 sizeof(...) 和 sizeof ...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47297871/