Why is invalid socket defined as ~0 in WinSock2.h (c++)?(为什么无效套接字在 WinSock2.h (c++) 中定义为 ~0?)
问题描述
在WinSock2.h中,invalid socket和socket error是这样定义的?这有什么意义吗?
In WinSock2.h, the invalid socket and socket error are defined as these? Is there any significance to this?
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
推荐答案
在二进制补码系统上(Windows 总是二进制补码),~0
等于 -1
,所以对编译器没有意义.
On a two's complement system (and Windows is always two's complement), ~0
is equal to -1
, so there's no significance to the compiler.
可能对读者有意义:~0
强调它是一个所有位都设置的值,而 -1
强调它是一个小于 0 的值 1.
There may be a significance to the reader: ~0
emphasizes that it's a value with all bits set, whereas -1
emphasizes that it's a value 1 less than 0.
旁白:
在不是二进制补码的系统上,假设 SOCKET
是无符号类型,通常 错误 写成 (SOCKET)(~0)代码>.原因是在这样的系统上,
~0
不代表值 -1,它是 INT_MIN
、负零或陷阱表示之一.因此,它不一定会转换为类型 SOCKET
作为所有位为零的值,而是将转换为 INT_MAX+2
、0
或goodness-knows-what(也许是所有位设置的值).
On a system which is not two's complement, and assuming that SOCKET
is an unsigned type, it is generally wrong to write (SOCKET)(~0)
. The reason is that on such systems, ~0
does not represent the value -1, it's one of INT_MIN
, negative zero, or a trap representation. Hence it will not necessarily convert to type SOCKET
as the value with all bits zero, rather it will convert as INT_MAX+2
, 0
, or goodness-knows-what (perhaps the value with all bits set).
所以通常你应该用 -1
初始化无符号类型以获得所有位设置的值.你可以使用UINT_MAX
,或~0UL
,或类似的,如果你知道你正在处理的无符号类型.但这并不值得,因为 -1
适用于所有无符号类型.
So generally you should initialize unsigned types with -1
to get the value with all bits set. You could use UINT_MAX
, or ~0UL
, or similar, if you know which unsigned type you're dealing with. But it's not worth it, because -1
works for all unsigned types.
这篇关于为什么无效套接字在 WinSock2.h (c++) 中定义为 ~0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么无效套接字在 WinSock2.h (c++) 中定义为 ~0?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01