A for loop iterating over the complete range of a variable

J

Joona I Palaste

Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable. As you all know, Skybuck's method won't work.
There are a number of other ways. You could use a wider type to do the
counting, but that would be cheating. You could also handle either the
first or last iteration as a special case outside the loop, but then it
would be more than a loop. You could make a very big array of integer
flags to tell whether you've already visited a value, but that would
consume too much memory.
So I settled down to this version. Assume unsigned short is 16 bits
wide.

int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

Any more elegant solutions out there?
 
A

Arthur J. O'Dwyer

Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable. As you all know, Skybuck's method won't work.
There are a number of other ways. You could use a wider type to do the
counting, but that would be cheating. You could also handle either the
first or last iteration as a special case outside the loop, but then it
would be more than a loop. You could make a very big array of integer
flags to tell whether you've already visited a value, but that would
consume too much memory.
So I settled down to this version. Assume unsigned short is 16 bits
wide.

int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

Any more elegant solutions out there?

I'm sure you've seen the solution that gets posted every time someone
claims it's hard to do:

unsigned short i = 0;
do {
/* do something */
} while (++i != 0);

It's not a 'for' loop, but it works and is easy to remember and write.
I guess you could use a 'for' loop similar to yours, but it would still
be slower and use a temporary variable: [UNTESTED CODE]

unsigned short i;
int tmp;
for (tmp=0, i=0; i || !tmp; ++i, tmp=1) {
/* do something */
}

-Arthur
 
R

Richard Tobin

Joona I Palaste said:
int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

If you use a for loop, you are bound to need some extra variable, since
the test at the start has to succeed 65536 times and fail once, so you
need 65537 states.

You can avoid the use of an extra variable by using a do ... while
loop, which tests at the end and therefore needs to succeed only 65535
times:

i = 0;
do {
/* do something */
i++;
} while(i != 0);

-- Richard
 
E

Ed Morton

Joona said:
Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable. As you all know, Skybuck's method won't work.
There are a number of other ways. You could use a wider type to do the
counting, but that would be cheating. You could also handle either the
first or last iteration as a special case outside the loop, but then it
would be more than a loop. You could make a very big array of integer
flags to tell whether you've already visited a value, but that would
consume too much memory.
So I settled down to this version. Assume unsigned short is 16 bits
wide.

int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

Any more elegant solutions out there?

How about:

unsigned short i;
for (i=0; ++i;) {
/* do something */
}

For the general case where i might be getting incremented by some number
other than 1 and so won't necessarily have the value zero when it loops
around (e.g. 13 in the following example), this might be better:

unsigned short i, j;
for (i=0, j=0; i >= j; j=i, i+=13) {
/* do something */
}

Regards,

Ed.
 
C

Christian Bau

Joona I Palaste said:
Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable. As you all know, Skybuck's method won't work.
There are a number of other ways. You could use a wider type to do the
counting, but that would be cheating. You could also handle either the
first or last iteration as a special case outside the loop, but then it
would be more than a loop. You could make a very big array of integer
flags to tell whether you've already visited a value, but that would
consume too much memory.
So I settled down to this version. Assume unsigned short is 16 bits
wide.

int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

Any more elegant solutions out there?

i = 0;
do {
<statements>
++i;
} while (i != 0);

Doing the same for signed int in a portable way seems to be difficult.
 
C

CBFalconer

Joona said:
Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable. As you all know, Skybuck's method won't work.
There are a number of other ways. You could use a wider type to do the
counting, but that would be cheating. You could also handle either the
first or last iteration as a special case outside the loop, but then it
would be more than a loop. You could make a very big array of integer
flags to tell whether you've already visited a value, but that would
consume too much memory.
So I settled down to this version. Assume unsigned short is 16 bits
wide.

int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
}

Any more elegant solutions out there?

You need a loop that postpones the test until after the first
iteration. For example:

unsigned int i;

i = -1;
do {
i++;
/* stuff */
} while (i < UINT_MAX);

or

i = 0;
do {
/* stuff */
} while (0U != ++i);
 
K

Keith Thompson

Christian Bau said:
i = 0;
do {
<statements>
++i;
} while (i != 0);

Doing the same for signed int in a portable way seems to be difficult.

int i = INT_MIN;
while (1) {
<statements>
if (i == INT_MAX) break;
i ++;
}

(Don't try this at home; depending on how fast your machine is,
iterating over a 32-bit int type could take several minutes and annoy
other users.)
 
B

Ben Pfaff

Keith Thompson said:
(Don't try this at home; depending on how fast your machine is,
iterating over a 32-bit int type could take several minutes and annoy
other users.)

Most home machines are single-user :)
 
T

Tim Rentsch

Joona I Palaste said:
Reading Skybuck Flying's obvious troll message, I thought of how to
properly do a for loop that would iterate over the complete range of
an unsigned variable.

[snip]

Any more elegant solutions out there?


The code


if( i = LOWER_BOUND, i <= UPPER_BOUND ) do {

/* stuff to do */

} while( i++ != UPPER_BOUND );


does the loop body once for each value of 'i' in the closed
interval [ LOWER_BOUND .. UPPER_BOUND ] whatever the bounds are (*),
and doesn't rely on any wraparound tricks. Any decent compiler
would optimize away the initial test if LOWER_BOUND and UPPER_BOUND
were known at compile time.

(*) As long as they are inside the range of the type of 'i'.
Being outside the range should also should be detected by
any reasonably decent compiler.
 
P

pete

unsigned short i = 0;
} while (++i != 0);

Those ain't elegant.
++i;
means the same thing as
i = i + 1;

If INT_MAX equals USHRT_MAX, as it may,
then you have undefined behavior when i has the value of INT_MAX
and you try to increment it.
 
A

Arthur J. O'Dwyer

unsigned short i = 0; [...]
} while (++i != 0);

Those ain't elegant.
++i;
means the same thing as
i = i + 1;

If INT_MAX equals USHRT_MAX, as it may,
then you have undefined behavior when i has the value of INT_MAX
and you try to increment it.

I guess you're right. What's the fix? Would

} while (i=(unsigned short)i+(unsigned short)1);

fix the UB? (And also, it seems odd that '++i' should mean the same
as 'i=i+1', promotions and all; can I have C&V for that, please?)

-Arthur
 
B

Ben Pfaff

Arthur J. O'Dwyer said:
(And also, it seems odd that '++i' should mean the same
as 'i=i+1', promotions and all; can I have C&V for that, please?)

That one's easy. First, in section 6.5.3.1:

2 The value of the operand of the prefix ++ operator is incremented. The result is the new
value of the operand after incrementation. The expression ++E is equivalent to (E+=1).
See the discussions of additive operators and compound assignment for information on
constraints, types, side effects, and conversions and the effects of operations on pointers.

Then in section 6.5.16.2:

3 A compound assignment of the form E1 op = E2 differs from the simple assignment
expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.
 
P

pete

Arthur said:
unsigned short i = 0; [...]
} while (++i != 0);

Those ain't elegant.
++i;
means the same thing as
i = i + 1;

If INT_MAX equals USHRT_MAX, as it may,
then you have undefined behavior when i has the value of INT_MAX
and you try to increment it.

I guess you're right. What's the fix? Would

} while (i=(unsigned short)i+(unsigned short)1);

fix the UB?

No.
(sizeof((short)0 + (short)0)) equals (sizeof(int)).
 
P

Peter Nilsson

Arthur J. O'Dwyer said:
Arthur said:
unsigned short i = 0; [...]
} while (++i != 0);

Those ain't elegant.
++i;
means the same thing as
i = i + 1;

If INT_MAX equals USHRT_MAX, as it may,
then you have undefined behavior when i has the value of INT_MAX
and you try to increment it.

I guess you're right. What's the fix? Would

} while (i=(unsigned short)i+(unsigned short)1);

fix the UB?

No. Even though you cast the operands of +, they are still subject to
integral promotion prior to the addition taking place.

The fix is trivial though...

unsigned short i = 0;
do {

} while (i += 1u);
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top