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?
				
        
 
            
        - STL 中有 dereference_iterator 吗? 2022-01-01
 - 从python回调到c++的选项 2022-11-16
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - C++ 协变模板 2021-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 近似搜索的工作原理 2021-01-01
 - 静态初始化顺序失败 2022-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 - Stroustrup 的 Simple_window.h 2022-01-01
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 
						
						
						
						
						
				
				
				
				