为什么在WinSock2.h(c ++)中将无效套接字定义为〜0? [英] Why is invalid socket defined as ~0 in WinSock2.h (c++)?

查看:89
本文介绍了为什么在WinSock2.h(c ++)中将无效套接字定义为〜0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinSock2.h中,无效的套接字和套接字错误定义为这些吗?有什么意义吗?

#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)

解决方案

在二进制补码系统(Windows始终是二进制补码)上,~0等于-1,因此对编译器没有意义. /p>

对读者可能有重要意义:~0强调这是一个所有位都已设置的值,而-1强调这是一个小于0的值.

在旁边:

在不是二进制补码的系统上,并且假设SOCKET是无符号类型,通常写(SOCKET)(~0)错误.原因是在这样的系统上,~0不代表值-1,它是INT_MIN,负零或陷阱表示之一.因此,它不一定会转换为类型SOCKET作为所有位为零的值,而是会转换为INT_MAX+20或善意-什么(也许是将所有位都设置为零的值).

因此,通常应使用-1初始化无符号类型,以获取设置了所有位的值.如果您知道要处理的是无符号类型,则可以 使用UINT_MAX~0UL或类似名称.但这不值得,因为-1适用于所有无符号类型.

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)

解决方案

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.

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.

Aside:

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).

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆