在 typedef 上使用 sizeof 而不是局部变量

Using sizeof on a typedef instead of a local variable

本文关键字:局部变量 sizeof typedef      更新时间:2023-10-16

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

typedef int type;
int main()
{
    char type;
    printf("sizeof(type) == %zun", sizeof(type)); // Outputs 1
}

输出始终为局部变量 type 的大小。

当C++消除了每次使用结构之前编写struct的需要时,它仍然保留了struct {type}语法,并引入了一个别名(class {type})来明确地引用结构或类。

示例(C++):

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

我的问题是是否有办法在 C 或 C++ 中显式引用typedef。也许sizeof(typedef type)这样的东西(但这不起作用)。

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

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

范围解析运算符::

printf("sizeof(type) == %zun", sizeof(::type));

在 C 中,这是不可能的。您正在隐藏类型 type .声明 char 后,不能将其用作类型:

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

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

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

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

C++具有范围解析运算符::您可以使用该运算符使用限定名称引用类型,即 ::typemy_namespace::type .

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

printf("sizeof(::type) == %un", sizeof(::type));

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

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

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

这也将给出答案为 4。