loop for all values of ushort ports using ushort index .... with caution.

P

pete

Ralf said:
Peter said:
[about:]
unsigned short port = 0;
do { [...]
} while (++port != 0);
It's undefined if INT_MAX equals USHRT_MAX.

while ((port += 1u) != 0);

That won't do what you want,
if UINT_MAX is greater than USHRT_MAX.

Would you care to explain?
Yes.

The loop (in this sub-thread) was
meant to iterate over all unsigned values.

No, it wasn't.
My comment "It's undefined if INT_MAX equals USHRT_MAX.",
refers to the increment operator causing a promotion
of type unsigned short, to type int.
(1 + INT_MAX) is undefind.
(++port) means exactly the same thing as (port = port + 1).

Peter Nilsson addressed that issue by replacing
++port with (port += 1u), thus causing the promotion to be to
type unsigned.
(1 + UINT_MAX) *is* defined as zero.
But then, as I said, the loop will do more
than just all of the values for unsigned short
if UINT_MAX is greater than USHRT_MAX.
 
P

Peter Nilsson

pete said:
pete said:
Peter Nilsson wrote:
unsigned short port = 0;
do { [...]
} while (++port != 0);

It's undefined if INT_MAX equals USHRT_MAX.

while ((port += 1u) != 0);

That won't do what you want,
if UINT_MAX is greater than USHRT_MAX.
... the loop will do more
than just all of the values for unsigned short
if UINT_MAX is greater than USHRT_MAX.

How so? The type of port, and therefore (port += 1u),
is unsigned short.

(unsigned short) (USHRT_MAX + 1u) == 0

If port has the value USHRT_MAX in the do/while body,
then it will have the value 0 on evaluation of the
conditional expression, hence the loop will break.
 
P

pete

Peter said:
pete said:
pete wrote:
Peter Nilsson wrote:
[about:]
unsigned short port = 0;
do {
[...]
} while (++port != 0);

It's undefined if INT_MAX equals USHRT_MAX.

while ((port += 1u) != 0);

That won't do what you want,
if UINT_MAX is greater than USHRT_MAX.
... the loop will do more
than just all of the values for unsigned short
if UINT_MAX is greater than USHRT_MAX.

How so? The type of port, and therefore (port += 1u),
is unsigned short.

(unsigned short) (USHRT_MAX + 1u) == 0

If port has the value USHRT_MAX in the do/while body,
then it will have the value 0 on evaluation of the
conditional expression, hence the loop will break.

You're right.
I'm wrong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,160
Latest member
CollinStri
Top