在 typedef 上使用 sizeof 而不是局部变量
Using sizeof on a typedef instead of a local variable
就像在这个例子中一样(在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++具有范围解析运算符::
您可以使用该运算符使用限定名称引用类型,即 ::type
或my_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。
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 离开范围后如何保护局部变量的值?
- 局部变量名称冲突
- C++ lambda:如何'freeze'局部变量的值?
- 我应该使我的局部变量常量还是可移动的
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 返回对局部变量 - C++ 的引用
- 是否可以影响 C++ 中回调函数的局部变量?
- 警告 C4101 未引用的局部变量
- 在 typedef 上使用 sizeof 而不是局部变量