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?
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
