c++ - sizeof运算符为VOID运算符返回1个字节

标签 c++ operators sizeof

我在看C++中的sizeof运算符。我遇到了意外的语义错误。我读过无效数据类型没有内存大小。但是,在我的程序中,sizeof运算符对于无效数据类型返回1。这怎么可能?

#include<iostream>
int main()
{
     std::cout<<"Void: "<<sizeof(void)<<" bytes\n";
     return 0;
}

我正在使用CodeBlocks编写代码,并且我的操作系统是Windows 10 x64。

最佳答案

这是一个GCC extension:

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

The option -Wpointer-arith requests a warning if these extensions are used.

关于c++ - sizeof运算符为VOID运算符返回1个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832014/

相关文章:

c++ - std::basic_fstream 和 std::unique_lock 的接口(interface)设计

C++ 应用程序不会终止

c++ - 内联函数不能包含递归、转到循环等?

c++ - 如何连接 wxWidgets、GTK2 小部件和 X11 窗口?

c - 根据字符串输入返回 sizeof

javascript - 为什么 ~-1 等于 0 而 ~1 等于 -2?

c# - 如何在 C# 泛型类型参数中强制支持某些运算符?

c++ - C++11 中的 move 语义

c - 对齐如何与指向零大小数组的指针一起使用?

c - 为什么我的代码中的 realloc() 和 free() 会失败?