To make an infinite loop, while(1) tends to generate lint/compiler warnings,
for(;;) does not.
Other than personal preference, are there any other technical reasons to
pick one over the other?
I will stipulate for the argument that performance is identical.
--
Scott
Validated Software
Lafayette, CO
__________ Information from ESET NOD32 Antivirus, version of virus signature database 4661 (20091204) __________
The message was checked by ESET NOD32 Antivirus.
No. Both forms are common C idioms; use whichever is more convenient.
("while(1)" might be clearer than "for(;;)" to someone who doesn't
know C very well, but I wouldn't worry about that.)
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
This sounds pretty bogus to me, Malcolm.
Plenty of C-like languages (C++ and Java certainly, probably C# too)
will accept for(;;) as an infinite loop.
And it's such a common idiom in C, that if someone reading C code
doesn't understand it and doesn't have the gumption to look up what it
means, then they're not very likely to get much out of the rest of the
code.
for(;;) is also much more elegant and compact than while(1), avoiding as
it does that ugly pseudo-boolean constant.
I suppose a really poor implementation could "evaluate" the "1" every time
through the loop, comparing it to non-zero.
Aside from that, it's personal preference.
My preference is "for(;;)" since it naturally (to me, anyway) reads "forever".
--
Kenneth Brody
> for(;;) is also much more elegant and compact than while(1), avoiding as
> it does that ugly pseudo-boolean constant.
While we're talking about aesthetics, then both for() and while() are
cleaner.
There's a condition missing from the while statement, but then there's also
one missing from the for(;;).
--
Bartc
If you mean literally "for()" and "while()", I hardly think that the
aesthetics of code that won't compile is relevant. I personally like
loop
...
end loop;
but that's not C either.
That's a minor detail. I don't think allowing an empty condition on while(),
to match the empty one in for(;;), or taking those two semicolons as read
(since they are not separating or terminating anything), is too taxing for
compiler maintainers.
(And for all I know, extensions might already exist for those.)
> I personally like
>
> loop
> ...
> end loop;
>
> but that's not C either.
No, that's a completely different syntax style and certainly not C. I'm
talking about being allowed to leave out one or two characters which don't
contribute anything.
--
Bartc
Typing 1 or ;; is even less taxing.
> (And for all I know, extensions might already exist for those.)
Not that I've ever seen.
If you're suggesting a change to the language (it wasn't immediately
clear to me that that was what what you meant), I don't think
this one carries its weight. It would be easy enough for compiler
writers to implement, but the benefit would be minimal -- and any
code that used the new forms wouldn't compile with compilers that
don't yet implement them.
C already has two idiomatic ways to express an infinite loop.
I see no advantage in adding a third and a fourth.
>> I personally like
>>
>> loop
>> ...
>> end loop;
>>
>> but that's not C either.
>
> No, that's a completely different syntax style and certainly not
> C. I'm talking about being allowed to leave out one or two characters
> which don't contribute anything.
They contribute correctness.
I prefer C but am paid to do xBASE.
--
Joe Wright
"If you rob Peter to pay Paul you can depend on the support of Paul."
Sorry for the digression, but:
Using Pascal in college, my friend liked to use the significantly
less-clean:
repeat
...
until false;
which always made me giggle.
-Beej
I think, if you're going to extend the language, that:
do { ... }
without the while(...), would be the most intuitive infinite loop.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
You'll achieve *far* greater brevity by jettisoning all
that silly white space (comments are white space, too). Try
that first, then come back if you feel a need for even more
compression.
--
Eric Sosman
eso...@ieee-dot-org.invalid
<OT>
Actually, it's Ada. In this context, "loop" is like C's "while (1) {",
and "end loop;" is like C's "}". I'm not familiar with xBASE, but
from the snippets I just Googled it doesn't like it uses the same
syntax; I'm seeing see end-of-loop markers like "ENDDO" and "ENDFOR",
not "end loop".
</OT>
All of which is, of course, beside the point.
Even MIPS assembly language disguises the fact that in the instruction
set, an unconditional branch is actually represented like this:
BEQ zero, zero, target ;; zero denotes the always-zero R0 pseudo-register
in MIPS assembly language (and dis-assembly, e.g. by GNU binutils objdump),
it's usually written like this, which generates the same instruction:
B target
Thus, while (1) is less abstract than the unconditional branch in MIPS
assembly.
In C, however, we have
do
...
while(1);
which amounts to the same thing, doesn't it?
<grin>
--
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
Me: http://pitcher.digitalfreehold.ca/ | Just Linux: http://justlinux.ca/
---------- Slackware - Because I know what I'm doing. ------
Yes. But that's a more substantial syntax change.
And anyway someone will be along in a minute with some tacky macros to
emulate any loop construct you can think of, so the chances of even my
trivial suggestion making it into the language proper are minimal.
--
Bartc
> "Not Really Me" <sc...@validatedQWERTYsoftware.XYZZY.com> wrote
> in message news:
>>I assume this has come up before but I am getting nowhere with
>>searches.
>>
>> To make an infinite loop, while(1) tends to generate
>> lint/compiler warnings, for(;;) does not.
>>
>> Other than personal preference, are there any other technical
>> reasons to pick one over the other?
>>
>> I will stipulate for the argument that performance is
>> identical.
>>
> for(;;) is meaningless to anyone who doesn't know C,
Why do you say that? This construct works in PHP, Perl, ECMAScript,
and probably other languages that have C-like for loops.
> or even to
> someone with a reasonable but not extensive knowledge of the
> language.
Is it really that esoteric? Personally, it never seemed that way to
me.
<snip>
--
"Don't worry about efficiency until you've attained correctness."
~ Eric Sosman, comp.lang.c
Oh goodie, just what we need: another if/else ambiguity!
do
do { }
while (condition); /* oops, goes with the inner do. right? */
:)
#define FOREVER for (;;)
void foo()
{
FOREVER
{
/* [...] */
}
}
lol! I could not resist.
> "Not Really Me" <sc...@validatedQWERTYsoftware.XYZZY.com> wrote in
> message news:
>>I assume this has come up before but I am getting nowhere with
>>searches.
>>
>> To make an infinite loop, while(1) tends to generate lint/compiler
>> warnings, for(;;) does not.
>>
>> Other than personal preference, are there any other technical
>> reasons to pick one over the other?
>>
>> I will stipulate for the argument that performance is identical.
>>
> for(;;) is meaningless to anyone who doesn't know C,
Even assuming you meant "C or C-like languages", that's a bogus
argument. x <<= y & ~z; is meaningless to anyone who doesn't know C,
too. So?
> or even to
> someone with a reasonable but not extensive knowledge of the
> language. while(1) or while(true) is used by several programming
> lanauges to indicate infinite loops.
for(;;) is a perfectly good idiom which has the advantage of not
triggering diagnostics in some compilers.
<snip>
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
But it's far more true than false is! :-)
-Beej
No.
--
pete
> for(;;) is meaningless to anyone who doesn't know C,
C, is also meaningless to anyone who doesn't know C.
--
pete
>>
>> loop
>> ...
>> end loop;
>>
>> but that's not C either.
>
>No, that's a completely different syntax style and certainly not C.
It's actually pretty close to Fortran:
do
...
enddo
James Tursa
/root
--
Learn more or lose your rights!
http://www.guncontrolkills.com/
http://www.gunbanobama.com/
Learn more or lose your rights!
> That's pretty funny Richard - for all your negative words about
> Antonius, you've just copied his post almost word for word!
It's hard to copy something you haven't seen. If he's actually said
something sensible for a change, however, I suppose we should
celebrate the novelty of the event.
You are right, but it's not at all obvious what for(;;) might do. You
have to look it up. It could easily be undefined behaviour or defined
that the loop is skipped entirely.
Personally I use while(true) which is legible and obvious.
--
Tim
"That excessive bail ought not to be required, nor excessive fines
imposed, nor cruel and unusual punishments inflicted"
Bill of Rights 1689
Fortran must have changed somewhat since the last time I used it (ie.
version IV).
But that brings up an interesting point: some languages seem happy to evolve
and to embrace new syntax, but some, like C, don't.
And I feel sure that the presence of the preprocessor in C has some
responsibility for this, by providing a poor man's way of adding 'new'
language constructs.
--
Bartc
> On 04/12/2009 22:56, Curtis Dyer wrote:
<snip>
> You are right, but it's not at all obvious what for(;;) might do.
> You have to look it up. It could easily be undefined behaviour or
> defined that the loop is skipped entirely.
>
> Personally I use while(true) which is legible and obvious.
I don't find for(;;) to be illegible, but I do find it AND while(true)
to be deceptive unless the loop truly is infinite. Personally I use
while(condition), which is legible, obvious, and accurate.
I'm not saying its illegible, but to me a for-loop implies that a loop
is going to run some predefined number of times, whereas a while-loop to
me implies that there will be some break/exit condition within it.
> Personally I use while(condition), which is legible, obvious, and accurate.
Ah, you mean while(true==true) or perhaps while(false==false) ??
<ducks and runs away>
Somehow I don't think RH would ever write such an infinite loop, as that
would imply having to escape from it using break, return, goto or exit()
instead.
--
Bartc
More importantly, it would imply having stdbool.h available, and
Heathfield's pride will never let him accept a C99 feature in his
sophomoric coding "style".
Sure, Dicky.
I think we all remember Han's damning exposure of the fake killfiling
behavior perpetrated by you, Thompson and the rest of your trolling
unit.
> If he's actually said something sensible for a change, however, I
> suppose we should celebrate the novelty of the event.
You may well celebrate, but it makes me extremely uneasy to learn that
there is something (albeit a minor stylistic question) on which I agree
with a man who shows such exceptionally poor taste on most other
matters.
For some reason (my aging eyesight, perhaps), I'm having
trouble finding function prototype syntax described in my
copy of K&R Classic. Would you mind telling me which pages
cover it?
It would be nice if you'd also point me to the description
of `...' variable-argument syntax.
Thanks!
--
Eric Sosman
eso...@ieee-dot-org.invalid
Just require a semicolon after the block if the while part is missing.
--
Mr. Antti-Juhani Kaijanaho, Jyvaskyla, Finland
If, as it seems, you are sarcastically implying that two urgently-needed
additions to the language in the 32 years since the publication of K&R
qualify C as "happy to evolve and embrace new syntax", there is more than
just your eyesight that is aging :)
-Adrian
My eyesight has a tendency to age at about the same rate
the rest of me does.
However, my point stands: bartc's observation is based on
an obvious falsehood. He also fails to consider that the
inventor of C (and the inventors of its predecessors) already
had knowledge of FORTRAN and COBOL and ALGOL and a sheaf of
other, older languages, and from the experience gained they
were able to get a "head start." FORTRAN/Fortran found it
necessary to add constructs that C already had; should C
respond by adding yet more constructs just so it can have
bragging rights? Pfui.
Maybe it's time to revive the COMEFROM statement.
--
Eric Sosman
eso...@ieee-dot-org.invalid
Actually, in spirit I agree completely with you :) I think C's
immutability is one of its strong points; no other language is so solidly
compatible. I was just amused that you were implying that the few
additions that _have_ been made since K&R qualified it as the 'evolving'
and 'embracing' language that bartc seemed to be wishing for.
I guess we were both just being a little sarcastic ;) No hard feelings.
Cheers,
Adrian
There have, of course, been many other changes to C. But
he specified "new syntax," and I didn't want to get into a silly
debate about whether new keywords (void, const, ...) and new
combinations (long long, long double) constituted "new syntax" or
just decorations to existing syntax. So I pointed out two changes
that are indisputably syntactic, beyond quibble.
> I guess we were both just being a little sarcastic ;) No hard feelings.
My sensayuma ages along with my eyesight ...
--
Eric Sosman
eso...@ieee-dot-org.invalid
> On 05/12/2009 11:32, Richard Heathfield wrote:
>> In<65Sdnd3_qqNPrYfW...@brightview.co.uk>, Tim Streater
>> wrote:
>>
<snip>
>>>
>>> Personally I use while(true) which is legible and obvious.
>>
>> I don't find for(;;) to be illegible, but I do find it AND
>> while(true) to be deceptive unless the loop truly is infinite.
>
> I'm not saying its illegible, but to me a for-loop implies that a
> loop is going to run some predefined number of times, whereas a
> while-loop to me implies that there will be some break/exit
> condition within it.
We obviously have very different ways of looking at while-loops. To
me, a while loop implies that the loop will continue until its
controlling condition becomes false; a break within the loop (and not
within an inner switch or loop) confuses the issue somewhat - not in
"obvious" code, but a lot of the breaks I've seen over the years have
been non-obvious and poorly- or un-documented.
>> Personally I use while(condition), which is legible, obvious, and
>> accurate.
>
> Ah, you mean while(true==true) or perhaps while(false==false) ??
No, I mean, for example:
while(!done)
{
done = stuff();
}
(which can be simplified, of course), or - if life's a little more
complicated than that:
while(!done)
{
pre_stuff();
if(done = stuff())
{
post_stuff();
}
}
which, presumably, you would write as:
while(1)
{
pre_stuff();
if(stuff())
break;
post_stuff();
}
> <ducks and runs away>
Runs away is easy:
chmod -x foo
I'm not so sure about ducks, though.
> "Tim Streater" <timst...@waitrose.com> wrote in message
> news:1aOdndmK75zV0YfW...@brightview.co.uk...
>> On 05/12/2009 11:32, Richard Heathfield wrote:
<snip>
>>
>>> Personally I use while(condition), which is legible, obvious, and
>>> accurate.
>>
>> Ah, you mean while(true==true) or perhaps while(false==false) ??
>
> Somehow I don't think RH would ever write such an infinite loop, as
> that would imply having to escape from it using break, return, goto
> or exit() instead.
I would normally avoid it, yes. I have on occasion written infinite
loops (using for(;;)), but only (IIRC) when the loop truly was
infinite within the terms of the program itself - i.e. the program
was not self-terminating. (Clearly it could be killed externally,
either via the OS or via a power cycle.) I don't often write such
programs in C, however.
>
> However, my point stands: bartc's observation is based on
>an obvious falsehood. He also fails to consider that the
>inventor of C (and the inventors of its predecessors) already
>had knowledge of FORTRAN and COBOL and ALGOL and a sheaf of
>other, older languages, and from the experience gained they
>were able to get a "head start." FORTRAN/Fortran found it
>necessary to add constructs that C already had;
True. They eventually formalized structs (user defined types in
Fortran lingo), dynamic memory allocation, and pointers (although a
Fortran pointer has type, base address, shape (number of dimensions
and extents of dimensions), and stride (are the dimensions contiguous
or interleaved in memory) information built in to the pointer), which
could be argued were inspired by other languages like C I suppose. And
Fortran has formalized iteroperability with C to make C/Fortran
inter-calling standardized. But Fortran also added a bunch of other
stuff making it fundamentally an array based language. Whole array
assignments, array slices used in calculations, automatically passing
array shapes in function calls, etc., are now all part of the
standard. This is quite a ways beyond what C has available when
working with arrays.
> should C
>respond by adding yet more constructs just so it can have
>bragging rights?
With Variable Length Arrays (VLA), it could be argued that C *has*
adopted something from other languages. Now, I don't really know what
the motivation was for VLA (other languages or just a general desire
to add useful functionality), but VLA is basically the same thing as
conformable arrays in Fortran which has been around for decades.
James Tursa
>> I'm not saying its illegible, but to me a for-loop implies that a
>> loop is going to run some predefined number of times, whereas a
>> while-loop to me implies that there will be some break/exit
>> condition within it.
>
> We obviously have very different ways of looking at while-loops. To
> me, a while loop implies that the loop will continue until its
> controlling condition becomes false; a break within the loop (and not
> within an inner switch or loop) confuses the issue somewhat - not in
> "obvious" code, but a lot of the breaks I've seen over the years have
> been non-obvious and poorly- or un-documented.
Well, it depends. Typically when I write such a loop there may be
several breaks depending on what has actually occurred, typically error
conditions. If I'm reading text from the network and parsing it, I can
have network errors, unexpected or incorrect text from the remote end,
database errors while I try to save the text, ...
That is not amenable to a simple while (!done) { done=stuff(); } sort of
construct.
>> <ducks and runs away>
>
> Runs away is easy:
> chmod -x foo
>
> I'm not so sure about ducks, though.
Foo Manchu, Ducky ??
I definitely don't think of for loops that way.
unsigned bit_count(unsigned n)
{
unsigned count;
for (count = 0; n != 0; n &= n - 1) {
++count;
}
return count;
}
unsigned gray_to_binary(unsigned gray)
{
unsigned binary;
for (binary = 0; gray != 0; gray >>= 1) {
binary ^= gray;
}
return binary;
}
--
pete
Haven't you been running a timing test on an infinite
loop for the past few years? Any results yet?
--
Eric Sosman
eso...@ieee-dot-org.invalid
<snip>
> Haven't you been running a timing test on an infinite
> loop for the past few years?
Yes.
> Any results yet?
Not yet. Patience is a virtue. If you are prepared to increase the
available budget, however, I may well be able to speed things up by a
significant percentage.
> Well, it depends. Typically when I write such a loop there may be
> several breaks depending on what has actually occurred, typically error
> conditions. If I'm reading text from the network and parsing it, I can
> have network errors, unexpected or incorrect text from the remote end,
> database errors while I try to save the text, ...
>
> That is not amenable to a simple while (!done) { done=stuff(); } sort of
> construct.
In general I agree with Richard H. I try to avoid several exits from a
block of code and try to stick with one return from a function. The
reason is not that code following that style is easier to read but that
it is easier to change. It also has the effect of making functions
shorter to be able to do this. Because if a function does one thing and
one thing only, then it reports on one thing as well.
If you have multiple fail conditions I would think that the above
becomes while (status != DONE) { status=stuff(); } //check status here
I have never regretted following this style, but I have several times
regretted not doing it.
--
Thomas.
Not Really Me wrote:
> I assume this has come up before but I am getting nowhere with searches.
>
> To make an infinite loop, while(1) tends to generate lint/compiler
> warnings, for(;;) does not.
>
> Other than personal preference, are there any other technical reasons to
> pick one over the other?
>
> I will stipulate for the argument that performance is identical.
>
I normally prefer while(true) because it's the most straight forward and
everyone knows it.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAksbwUgACgkQG6NzcAXitM+3GQCdHlJ6okASx172MOop/QBBsv9X
paUAoIsdnr6G1OLLcthGZtwTfZ51dRvD
=JOKN
-----END PGP SIGNATURE-----
Oh goodie! Just what we need, double semicolon!
do S ; /* semicolon required to denote infinite looping over S */
Now let S be the statement ``do { } while(condition); '' and we get:
do
do { }
while (condition);;
Oops!
You know, we should be developing a vaccine against the the semicolon
disease, not spreading it.
I'm not bothered by either. I always considered for(;;) to be obvious,
there is no termination condition so no termination. I consider while(1)
or while(true) to be obvious. I also consider "REPEAT UNTIL false" to be
obvious. I tend to use
for (;;)
I would also have no problem with
for (initialisation; ; iteration)
--
Flash Gordon
In C90, the identifier "true" is undeclared unless you've defined
it yourself (or it's defined by some header you've #included).
In C99, it's undeclared unless you have "#include <stdbool.h>" or,
as in C90, you've defined it yourself (which could create a conflict
if you later add "#include <stdbool.h>").
I wouldn't hesitate to write "while (true)" if I've already caused
"true" to be defined for some other reason, but I wouldn't introduce
it just for that purpose, since "while (1)" is such a common and
well known idiom.
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Yeah.
Of course this is a different double semicolon from the one in for (;;)
--
Bartc
You can have more than one, it's just you will only reach one of them on
any given run. There are even good reasons for doing this on occasion.
> If there is some (non-external) condition that terminates the loop,
> generally it should be in the condition that controls it. However this isn't
> always easy to arrange. A break/ goto is better than messing about with a
> flag which is introduced purely to avoid having a jump.
That's a matter of style/opinion. I've done things both ways.
--
Flash Gordon
What happens if a single program is comprised of multiple forms of separate
execution that do different things?
<snip>
> If there is some (non-external) condition that terminates the loop,
> generally it should be in the condition that controls it.
Right, but it's a style thing. Not everyone agrees with us.
> However this isn't always easy to arrange. A break/ goto is better
> than messing about with a flag which is introduced purely to avoid
> having a jump.
See? Even you disagree with us.
> >> But that brings up an interesting point: some languages seem happy to
> >> evolve and to embrace new syntax, but some, like C, don't.
>
> > For some reason (my aging eyesight, perhaps), I'm having
> > trouble finding function prototype syntax described in my copy of K&R
> > Classic. Would you mind telling me which pages cover it?
>
> > It would be nice if you'd also point me to the description
> > of `...' variable-argument syntax.
>
> If, as it seems, you are sarcastically implying that two urgently-needed
> additions to the language in the 32 years since the publication of K&R
> qualify C as "happy to evolve and embrace new syntax", there is more than
> just your eyesight that is aging :)
My K&R II has a publication dat of 1988. So according to you K&R I
came out 32 years earlier in 1956. That makes it older than Fortran!
In what way was the ... syntax "urgent"?
> >>> You are right, but it's not at all obvious what for(;;) might do.
there are lots of things in C that aren't obvious. No we ban ?: or
function pointers?
> >>> You have to look it up. It could easily be undefined behaviour or
> >>> defined that the loop is skipped entirely.
>
> >>> Personally I use while(true) which is legible and obvious.
>
> >> I don't find for(;;) to be illegible, but I do find it AND while(true)
> >> to be deceptive unless the loop truly is infinite.
>
> > I'm not saying its illegible, but to me a for-loop implies that a loop is
> > going to run some predefined number of times,
I try to follow that rule but C's for doesn't limit you that way.
> > whereas a while-loop to me
> > implies that there will be some break/exit condition within it.
>
> >> Personally I use while(condition), which is legible, obvious, and
> >> accurate.
>
> > Ah, you mean while(true==true) or perhaps while(false==false) ??
>
> Somehow I don't think RH would ever write such an infinite loop, as that
> would imply having to escape from it using break, return, goto or exit()
> instead.
Some embedded systems may run for ever, or at least never terminate by
programmatic (it's a word?) reasons.
K&R1 was published, if I recall correctly, in 1978, 31 years ago. If
it was early in the year 32 years is a more accurate figure.
my point was they didn't wait 31/32 years before adding new syntax.
They waited 10. And more new syntax was added in 1999.
<snip>
> Some embedded systems may run for ever, or at least never terminate
> by programmatic (it's a word?) reasons.
"self-terminate" might be a useful term to invent at this point. We
could define a self-terminating program as one which can terminate
simply by following the rules of the language. Thus, this program is
self-terminating:
#include <stdio.h>
int main(void)
{
int ch;
while((ch = getchar()) != EOF)
{
continue;
}
return 0;
}
because, at least in theory, it is possible for the program logic to
reach one of C's ways of terminating the program (exit() and return
from main() being the most important, though there is at least one
more), even though it might be sat waiting for the stream, and even
though the stream might simply be piped from:
#include <stdio.h>
int main(void)
{
for(;;)
{
putchar('\n');
}
return 0;
}
(which is not self-terminating).
I think that both are same, either you go with for(;;) or while(1).
But i guess, on the internal workings, while(1) is far better than for
(;;) [ even though, for(;;) is cleaner to read ]. The reason being,
while implementing the for(;;), the code has to maintain an internal
variable, for incrementing it and checking for infinity [ Correct me
if am wrong ], whereas in the case of while(1), its just a flag check
and nothing more.
So, i would prefer to use while(1) than for(;;), at the cost of the
readability.
Roopesh.
<snip>
> I think that both are same, either you go with for(;;) or while(1).
> But i guess, on the internal workings, while(1) is far better than
> for (;;) [ even though, for(;;) is cleaner to read ]. The reason
> being, while implementing the for(;;), the code has to maintain an
> internal variable, for incrementing it and checking for infinity [
> Correct me if am wrong ],
You're wrong. The compiler is under no such obligation.
> whereas in the case of while(1), its just
> a flag check and nothing more.
Not even that. Both for(;;) and while(1) can be implemented as:
:label
stuff
jmp label
> So, i would prefer to use while(1) than for(;;), at the cost of the
> readability.
If that's your only reason, you can now revert to for(;;).
I used infinite loop to mean one which uses an explicit break somewhere in
the body.
I use them all the time, mainly because when I start to write one, I have
little idea how I'm going to jump out it. And later I don't bother to change
it to conventional form.
--
Bartc
while(1)
{
tick();
waitforframesynch();
}
you see this type of thing quite a lot. In this case, the program has to
draw something to the screen every frame, so the outer loop imposes that
condition. It won't terminate until the prgram itself is terminated (often
by the device being powered down).
>
> I use them all the time, mainly because when I start to write one, I have
> little idea how I'm going to jump out it. And later I don't bother to
> change it to conventional form.
>
If you terminate when game over, I'd write the loop
while( ! gameover() )
{
tick();
waitforframesynch();
}
this
while(1)
{
tick();
if(gameover())
break;
watiforframesynch();
}
is in my opinion sloppy.
However this
int gameflag = 1;
while(gameflag)
{
tick();
if(gameover())
gameflag = 0;
waitforframesynch();
}
is in my opinion worse, because you are creating an artificial bit of logic.
(As always with programming little snippets don't really show the issue. Any
short section of code is readily understandable. The problems come when the
loop control is buried in complicated non-loop instructions).
for (;;) {
while (1) {
do {
otog:
...
goto otog;
} while (1);
}
}
--
Eric Sosman
eso...@ieee-dot-org.invalid
<snip>
> >>> You can have only one infinite loop in a program.
<snip>
> I used infinite loop to mean one which uses an explicit break somewhere in
> the body.
whilst other people use it to mean a loop that *never* terminates.
I've probably described for(;;) as "an infinite loop" even when I've
been sure it does terminate. But that is a a bit sloppy.
> I use them all the time, mainly because when I start to write one, I have
> little idea how I'm going to jump out it.
eeek! How can you write a loop without knowing how it will terminate!
Surely you construct the loop-invarient and termination criteria
*before* you write the loop!
:-)
> And later I don't bother to change
> it to conventional form.
I use the construct when none of the normal C-loop forms will do. That
is I want to break out of the middle of the loop. You can use an extra
boolean variable but sometimes that seems contrived.
for (;;)
{
skip_leading_whitespace (stream);
if (!build_msg (msg, stream))
break; /* <-- break out of loop */
process_msg (msg);
}
Aargh! Sorry but I was hoping for "valid" reaons. In C99, the conditions
are stated as optional in a for statement, but they are mandatory for while.
--
Scott
Validated Software
Lafayette, CO
__________ Information from ESET NOD32 Antivirus, version of virus signature database 4667 (20091207) __________
The message was checked by ESET NOD32 Antivirus.
That's as bad as my friend who liked:
#define WahDiddy while(1)
do {
...
} WahDiddy;
Maybe you had to grow up in the sixties here in the US.
Thanks Pete. Best answer of the bunch. It is what I expected, but I needed
to ask.
--
Scott
Validated Software
Lafayette, CO
__________ Information from ESET NOD32 Antivirus, version of virus signature database 4667 (20091207) __________
ITYM:
#define ever (;;)
void foo()
{
for ever
{
/* ... */
}
}
> lol! I could not resist.
Ditto.
--
Kenneth Brody
"while (!done)" is common for me for loops that have more than one "obvious"
terminal condition.
--
Kenneth Brody
How do you feel about "continue"?
while (!done)
{
done = stuff();
if (done)
continue;
done = more_stuff();
}
Pretty lame, I admit. I suppose "continue" could be thought of as "goto in
disguise"?
--
Kenneth Brody
I think Adrian's point was that significant new syntax (prototypes and
"...") was added once in that 31/32 year period (the C99 syntax
changes were relatively minor).
Yes.
> But i guess, on the internal workings, while(1) is far better than for
> (;;)
No. I would say the reverse.
> [ even though, for(;;) is cleaner to read ]. The reason being,
> while implementing the for(;;), the code has to maintain an internal
> variable, for incrementing it and checking for infinity [ Correct me
> if am wrong ],
You are wrong. C for loops to not rely on a loop counter even
conceptually. for (;;) reads...
Do no initialiastion
{
Do not check a condition
Do loop body
Do not do anything for moving on to the next iteration
}
So the for loop is saying explicitly that you do not have a condition.
In C, if you want a conceptual loop counter you have to explicitly
provide it.
> whereas in the case of while(1), its just a flag check
> and nothing more.
True.
> So, i would prefer to use while(1) than for(;;), at the cost of the
> readability.
Well, your reasoning is wrong. In any case, the compiler can implement
it with an unconditional jump, and I've yet to see one that implements a
test.
--
Flash Gordon
You are wrong. Most/a huge percentage of C for loops do indeed rely on
a loop counter.
A bit silly perhaps but I like the following:
Use the preprocessor directive
#define EVER ;;
then you can use
for(EVER)
{
stuff
}
for the infinite loop
<snip>
> A bit silly perhaps but I like the following:
>
> Use the preprocessor directive
>
> #define EVER ;;
This macro invades space reserved by the Standard for future
expansion. This is perhaps unlikely to cause a problem, although it's
not beyond the bounds of possibility that some future C Standard
might define EVER as an error code (wrong version of Windows,
mayhap?).
<snip>
When I was young and stupid, I used to write
#define until(x) while(!(x))
so I could have `do { something } until(condition);'. It took
me a while to understand that this made my code *less* readable
rather than more, because the reader encountering the latter had
to stop and go hunt for the definition of `until'. Interrupting
the reader's train of thought was not helpful.
Somebody handed down a Commandment along the lines of "Thou
shalt not use the preprocessor to muck up the syntax," but I
can't find the original and don't know the identity of the God
whose command it was. Personally, I think it must have been a
false God, because every so often one comes across an inspired
use that *does* do violence to the syntax, and does it for a
good reason. But things like `until' and `EVER' are just silly;
"beautiful new impediments to understanding" as the real, true
Ten Commandments puts it.
--
Eric Sosman
eso...@ieee-dot-org.invalid
> Somebody handed down a Commandment along the lines of "Thou
> shalt not use the preprocessor to muck up the syntax," but I
> can't find the original and don't know the identity of the God
> whose command it was. Personally, I think it must have been a
> false God, because every so often one comes across an inspired
> use that *does* do violence to the syntax, and does it for a
> good reason. But things like `until' and `EVER' are just silly;
> "beautiful new impediments to understanding" as the real, true
> Ten Commandments puts it.
My favorite additions to syntax are macros that allow one to
iterate over a custom data structure without manually writing out
extensive "for (...)" syntax.
--
"IMO, Perl is an excellent language to break your teeth on"
--Micah Cowan
You missunderstood me. The C for loop does not rely on a loop counter.
Of course, many loops make use of a loop counter, and as I stated, but
you snipped without marking the snippage, when you use a loop counter
you have to do so explicitly.
It is also clear from what the OP posted what I was refuting.
--
Flash Gordon
Actually, there is one technical reason that has not been mentioned yet...
Funny it took pete's blunt answer to make me remember it:
for(;;) is a blunt, obvious looping contruct.
while(1) on the other hand can be confused with while(l)
this is imho a good reason to avoid both while(1) and local variables named
l
--
Chqrlie.
> "Not Really Me" <sc...@validatedQWERTYsoftware.XYZZY.com> a écrit dans le
Crikey, do you also avoid using the integer 1 in case people confuse
it for l?
I really can't think of a worse reason not for using while(1). What font
do you use? my "1" looks nothing like an "l".
--
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c
Interesting.
I've seen the visual similarity of the digit '1' and the letter
'l' presented as a reason (and a very good one IMHO) to avoid using
'l' as an identifier. I've never seen it presented as a reason to
avoid using the number 1.
> "Not Really Me" <sc...@validatedQWERTYsoftware.XYZZY.com> a écrit dans le
> message de news: 7o4kd2F...@mid.individual.net...
>> pete wrote:
>>> Not Really Me wrote:
>>>> I assume this has come up before but I am getting nowhere with
>>>> searches. To make an infinite loop, while(1) tends to generate
>>>> lint/compiler
>>>> warnings, for(;;) does not.
>>>>
>>>> Other than personal preference, are there any other technical
>>>> reasons to pick one over the other?
>>>
>>> No.
>>
>> Thanks Pete. Best answer of the bunch. It is what I expected, but I
>> needed to ask.
>
> Actually, there is one technical reason that has not been mentioned yet...
> Funny it took pete's blunt answer to make me remember it:
>
> for(;;) is a blunt, obvious looping contruct.
>
> while(1) on the other hand can be confused with while(l)
So? Instead of a constant 1, the programmer /could/ use any other non-zero
integral value. Thus
while (2)
is just as effective, and few people would confuse a 2 with a C identifier.
But, perhaps even better (from the readability point of view) would be to
use a tautology
while (1 == 1)
or
while (7 != 6)
accomplishes the same thing, but with an obvious "truth" value
> this is imho a good reason to avoid both while(1) and local variables
> named l
>
Having said all that, I prefer
for (;;)
over
while (1)
The programmer / reader has to evaluate the condition in the while () loop
and determine if it will always evaluate to true. Trivial for while (1) or
while (0), but not so trivial for other conditions. OTOH, the for (;;)
template leaves the reader/programmer with nothing to evaluate; if they see
no terminating condition, the loop doesn't terminate.
I know that these are trivial reasons, but that's how /I/ make my choice as
to which looping construct I'll use for infinite loops. Heck, it could be
worse. I /could/ use
some_label:;
/**/
goto some_label;
:-)
--
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
Me: http://pitcher.digitalfreehold.ca/ | Just Linux: http://justlinux.ca/
---------- Slackware - Because I know what I'm doing. ------
Good advice - it's not like the idiom for(;;){...} is that hard to
understand. On the other hand, I am basically a hobby programmer who
doesn't forsee my code ever being read let alone maintained by others,
so sometimes I adopt little idiosyncratic conventions for my own use.
> > my point was they didn't wait 31/32 years before adding new syntax.
> > They waited 10. And more new syntax was added in 1999.
>
> I think Adrian's point was that significant new syntax (prototypes and
> "...") was added once in that 31/32 year period (the C99 syntax
> changes were relatively minor).
designated initialisers?
1 (one) is one of the few numeric constants I allow in my code. 0
(zero) being the other one. Oh, ok some masks might sneak in.
> Good advice - it's not like the idiom for(;;){...} is that hard to
> understand. On the other hand, I am basically a hobby programmer who
> doesn't forsee my code ever being read let alone maintained by others,
> so sometimes I adopt little idiosyncratic conventions for my own use.
eventually though you become "the other".
Believe me, some of your old code will eventually look very odd to
you!
Oh, I believe you. I've already had cases where I ended up rewriting
from scratch a program that I had intended to merely modify bacause it
seemed easier than trying to figure out what the earlier program was
actually doing. So I do use things like comments and descriptive
variable names much more than I strictly need to. I no longer use my
EVER macro (mostly because of laziness rather than concern for long-
term readability - it's more typing) but thought it still somewhat
amusing.
In one of my more demented moments I wrote a program in Visual Basic
that used a boolean variable FatLadySings in the construct Do ... Loop
Until FatLadySings. It was part of a simulation of the child's game
CandyLand, so I was in a frivolous mood.
Mm. I said "after the block", not "after the statement". But good point, I
forgot C allows a single statement in that position.
--
Mr. Antti-Juhani Kaijanaho, Jyvaskyla, Finland
> In one of my more demented moments I wrote a program in Visual Basic
> that used a boolean variable FatLadySings in the construct Do ... Loop
> Until FatLadySings. It was part of a simulation of the child's game
> CandyLand, so I was in a frivolous mood.
#ifdef HELL_FROZEN
... some ifdef'd out code ...
#endif
> Kaz Kylheku <kkyl...@gmail.com> writes:
>>do S ; /* semicolon required to denote infinite looping over S */
>>Now let S be the statement ``do { } while(condition); '' and we get:
>
> The semicolon is required only in your phantasy.
>
> ISO/IEC 9899:1999 (E) reads:
>
> do statement while ( expression ) ;
>
> There is no �;� after �statement�.
Try telling your compiler that.
Putting on my Dilbert Dinosaur costume... Back in the early 80's I was a
one person consulting business. I finally hired a "receptionist/assitant".
She was a returning to work mother with grown kids. The first task I gave
her was to type an old basic program into the computer. You quessed? She
used lower case 'l' instead of 1 throughout the program. I was using
CBasic, so the code was entered in an editor, not a live basic interpreter.
Aargh!
--
Scott
Validated Software
Lafayette, CO
__________ Information from ESET NOD32 Antivirus, version of virus signature database 4673 (20091209) __________
> Charlie Gordon wrote:
>> "Not Really Me" <sc...@validatedQWERTYsoftware.XYZZY.com> a écrit
Not exactly a reason to limit competent programmers however.