c - 在这种情况下,C 是否正确处理了 sizeof(...) 和 sizeof ...?

标签 c sizeof unary-operator

在下面的代码中,函数testtest2是等价的吗?

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?
}

换句话说:

  1. sizeof(rofl) 中的 rofl 是否因为括号正确选择了 rofl type?<
  2. 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/

相关文章:

c - 干净地退出 C 函数

c++ - 如何获得模板参数包的最大成员?

c - printf 中的一元运算符

c++ - 有没有办法通过sizeof()来计算一个指向 vector 的大小?

c# - 一元运算符(+=、=+、++x 和 x++)之间的区别

c - 一元++优先顺序

c - 在文件中查找单词,检查它们是否是回文

c - 从行中读取单词

c++ - MASM 使用 VS 击败未优化的 .cpp 但不是未优化的 .c

c++ - 有没有办法通过类型单独获取 vector 的字节大小?