为什么无效套接字在 WinSock2.h (c++) 中定义为 ~0?

2022-01-19 00:00:00 sockets network-programming c++

在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+20 或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.

相关文章