473,388 Members | 1,298 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

A for loop iterating over the complete range of a variable

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?

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Ice cream sales somehow cause drownings: both happen in summer."
- Antti Voipio & Arto Wikla
Nov 14 '05 #1
16 1589
Joona I Palaste <pa*****@cc.helsinki.fi> scribbled the following:
So I settled down to this version. Assume unsigned short is 16 bits
wide.
Actually you don't need to assume that...
int stop = 0;
unsigned short i;
for (i=0; !stop; stop = ++i==0) {
/* do something */
} Any more elegant solutions out there?


--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"I wish someone we knew would die so we could leave them flowers."
- A 6-year-old girl, upon seeing flowers in a cemetery
Nov 14 '05 #2

On Sun, 29 Aug 2004, Joona I Palaste wrote:

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

Nov 14 '05 #3
In article <cg**********@oravannahka.helsinki.fi>,
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
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
Nov 14 '05 #4


Joona I Palaste wrote:
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.

Nov 14 '05 #5
In article <cg**********@oravannahka.helsinki.fi>,
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
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.
Nov 14 '05 #6
Joona I Palaste wrote:

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

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 14 '05 #7
Christian Bau <ch***********@cbau.freeserve.co.uk> writes:
[...]
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.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8
Keith Thompson <ks***@mib.org> writes:
(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 :-)
--
"Some people *are* arrogant, and others read the FAQ."
--Chris Dollin
Nov 14 '05 #9
Joona I Palaste <pa*****@cc.helsinki.fi> writes:
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.
Nov 14 '05 #10
Arthur J. O'Dwyer wrote:

On Sun, 29 Aug 2004, Joona I Palaste wrote:
unsigned short i;
for (i=0; !stop; stop = ++i==0) { Any more elegant solutions out there?

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.

--
pete
Nov 14 '05 #11

On Mon, 30 Aug 2004, pete wrote:

Arthur J. O'Dwyer wrote:
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
Nov 14 '05 #12
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> writes:
(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.

--
"I've been on the wagon now for more than a decade. Not a single goto
in all that time. I just don't need them any more. I don't even use
break or continue now, except on social occasions of course. And I
don't get carried away." --Richard Heathfield
Nov 14 '05 #13
Arthur J. O'Dwyer wrote:

On Mon, 30 Aug 2004, pete wrote:

Arthur J. O'Dwyer wrote:
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)).

--
pete
Nov 14 '05 #14
"Arthur J. O'Dwyer" <aj*@nospam.andrew.cmu.edu> wrote in message
news:Pi**********************************@unix48.a ndrew.cmu.edu...
On Mon, 30 Aug 2004, pete wrote:
Arthur J. O'Dwyer wrote:
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);

--
Peter
Nov 14 '05 #15

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
Keith Thompson <ks***@mib.org> writes:
(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 :-)


Yes, but if he does it, I'll still be annoyed about it. ;)
Nov 14 '05 #16
Keith Thompson wrote:
Christian Bau <ch***********@cbau.freeserve.co.uk> writes:
[...]
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 ++;


ITYM i++; ;-)

Sean
--
Sean Fao
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Brian L. | last post by:
After following the discussion on Generator expressions on python-dev for the last few weeks, and finally getting used to list comprehensions as opposed to map/filter, it occurred to me that the...
19
by: Stephan Aspridis | last post by:
Hi folks, a happy new year. I have a little problem with a program I am writing at the moment. A loop doesn't behave the way I'd like to (namely, the "break" is ignored). This is the code in...
63
by: Aaron Ackerman | last post by:
What is the sytax for exiting a for loop in C#?
13
by: algorimancer | last post by:
I use the STL collection classes a lot, and frequently find myself writing something like: vector<CDataClass>::iterator iter=DataClassCollection.begin(); vector<CDataClass>::iterator...
8
by: Jim Langston | last post by:
There's the thing about iterating though a map or vector when you may delete one of the elements, where you simply assign the iterator to the map.erase() statement or increment it if you don't. ...
14
by: petermichaux | last post by:
Hi, In the Yahoo! UI event.js file I see the following quite a bit for (var i=0,len=unloadListeners.length; i<len; ++i) { when I always just write for (var i=0; i<unloadListeners.length;...
35
by: erik gartz | last post by:
Hi. I'd like to be able to write a loop such as: for i in range(10): pass but without the i variable. The reason for this is I'm using pylint and it complains about the unused variable i. I can...
11
by: SM | last post by:
I have a couple of arrays that represent different categories. One array per category. The arrays contain names of photos. The arrays look like this: $cat_1 = array('moonlight.jpg'',...
7
by: Dave | last post by:
Hey there, having a bit of problem iterating through lists before i go on any further, here is a snip of the script. -- d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 c5...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.