Why is invalid socket defined as ~0 in WinSock2.h (c++)?

c++, network-programming, sockets

Solution

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.

Problem

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

Original source

Related problems