【问题标题】:Using sizeof on a typedef instead of a local variable在 typedef 上使用 sizeof 而不是局部变量
【发布时间】:2015-01-25 00:09:45
【问题描述】:

就像这个例子一样(在 C 中):

typedef int type;

int main()
{
    char type;
    printf("sizeof(type) == %zu\n", sizeof(type)); // Outputs 1
}

输出总是局部变量type的大小。

当 C++ 不再需要在每次使用结构之前编写 struct 时,它仍然保留了 struct {type} 语法并引入了别名 (class {type}) 来显式引用结构或类。

示例(在 C++ 中):

struct type {
    int m;
};

int main()
{
    char type;
    printf("sizeof(type) == %u\n", sizeof(type)); // Outputs 1
    printf("sizeof(struct type) == %u\n", sizeof(struct type)); // Outputs 4
    printf("sizeof(class type) == %u\n", sizeof(class type)); // Outputs 4
}

我的问题是,是否有办法在 C 或 C++ 中明确引用 typedef。可能是sizeof(typedef type) 之类的东西(但这不起作用)。

我知道对变量和类型使用不同的命名约定来避免这种情况是一种常见的做法,但我仍然想知道在语言中是否有办法做到这一点,或者是否没有。 :)

【问题讨论】:

  • 您的文件范围 typedef 和您的块范围 char 对象具有相同的名称。解决方法是重命名其中一个,以便您可以明确地引用它们。 (无论如何,type 是一个糟糕的类型名称,除非它实际上代表一种类型,例如在实现编译器或解释器的代码中。)
  • 由于这一行,这将无法完全编译:char type;变成char int;这将引发别名或屏蔽警告。在任何情况下,printf 将始终使用局部变量 'type'

标签: c++ c typedef sizeof type-alias


【解决方案1】:

没有办法解决这个问题,但如果你的结构是全局定义的,你可以使用它,

范围解析运算符 ::.

printf("sizeof(type) == %zu\n", sizeof(::type));

【讨论】:

  • @AlexFarber:是的,我刚刚注意到了。所以这个问题完全是关于范围的。
  • @Venkatesh:是的,你可以。但不是 typedef 和变量。但是这是合法的:int main() { struct type {}; int type; }
【解决方案2】:

在 C 中这是不可能的。您正在隐藏类型 type。声明char后就不能作为类型使用了:

typedef int type;

int main(void) {
    char type;
    type t;      // error: expected ‘;’ before ‘t'
    printf( "%d %d\n", sizeof type, sizeof t );
    return 0;
}

但是,如果您在声明 char 之前为 type 创建别名或声明 type,则可以使用它:

int main(void) {
    type t;
    char type;
    printf( "%d %d\n", sizeof type, sizeof t );
    return 0;
}


int main(void) {
    typedef type type_t;
    char type;
    printf( "%d %d\n", sizeof type, sizeof( type_t ) );
    return 0;
}

C++ 具有作用域解析运算符::,您可以使用它来引用使用限定名称的类型,即::typemy_namespace::type

【讨论】:

  • 我接受这个答案,因为我认为这是最好的答案。它告诉我如何引用被遮盖的 typedef 并且不依赖于 type 在全局范围内。
【解决方案3】:

在 C++ 中,使用 :: 运算符得到答案为 4。

printf("sizeof(::type) == %u\n", sizeof(::type));

:: 用于访问 C++ 中的全局变量。在C中,我认为没有直接的方法。您可以使用函数来完成。

:: 运算符即使不是类或结构也可以工作。

typedef int type1;

int main() {
 int type1;
 cout<<sizeof(::type1);
 return 0;
}

这也会给出 4 的答案。

【讨论】:

  • 没有struct typetype 不是一个类。你能在非类的东西上使用struct 类型介绍器吗?
  • @jrok 请阅读问题,对于 C++ 代码,他没有使用 typedef 和 struct。
  • @BenVoigt 抱歉有错字,我更新了我的答案。
猜你喜欢
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
相关资源
最近更新 更多