C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Using -1 as the max value for an unsigned integer

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 18 Jul 2025 07:35:49 -0700
On Friday, 18 July 2025 04:13:04 Pacific Daylight Time David Brown via Std-
Proposals wrote:
> Finally, I suggest you stop writing nonsense in your code. A TCP/IP
> port is a number between 1 and 65535 (UDP allows port 0 in some
> circumstances to mean "no port").

Which is why several frameworks use -1 to indicate "no port was specified"
because 0 can have a meaning. That is, it's effectively a
std::optional<uint16_t> and even has the same size as a plain int on all
modern architectures (though it would have a less strict alignment
requirement).

For example, take the following two URLs:
  proto://example.com/
  proto://example.com:0/

If these were given as a bind address, the first entry could mean "use the
default for 'proto'" whereas the second would mean "bind to port 0", which
causes the OS to allocate a free port at random.
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Platform & System Engineering

Received on 2025-07-18 14:35:55