473,412 Members | 2,048 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,412 software developers and data experts.

Reading a key inside a loop

When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed. Look at this sample:
------
while(1=1)
{
printf("oi");
ch=getchar();
if (ch=='q') break;
}

I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
(this program actually stop the printing of 'hi' and waits for a key
to be pressed. I dont want this!)
Sorry about the bad english

Mar 29 '07 #1
70 3439
On 29 Mar, 16:55, "hstagni" <sta...@gmail.comwrote:
When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed.
FAQ 19.1 - see http://c-faq.com/ or more particularly http://c-faq.com/osdep/cbreak.html
Look at this sample:
------
while(1=1)
What's wrong with for(;;) or while(1) ?
{
printf("oi");
ch=getchar();
if (ch=='q') break;

}

I want the program to print 'hi' forever
Well it won't do so when you've coded "oi"...

Mar 29 '07 #2

"hstagni" <st****@gmail.comha scritto nel messaggio
news:11*********************@n76g2000hsh.googlegro ups.com...
When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed. Look at this sample:
------
while(1=1)
{
printf("oi");
ch=getchar();
if (ch=='q') break;
}

I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
(this program actually stop the printing of 'hi' and waits for a key
to be pressed. I dont want this!)
Why do you want that?
Anyway, there is no portable way of doing that. It depends on what system
you're working on.
http://c-faq.com/osdep/cbreak.html
Mar 29 '07 #3
"hstagni" <st****@gmail.comha scritto nel messaggio
news:11*********************@n76g2000hsh.googlegro ups.com...
while(1=1)
This tries to assign 1 to 1. But you can't assign to a decimal constant.
You meant while (1==1), or, as mark_bluemel pointed out, while (1).
Mar 29 '07 #4
On 29 Mar 2007 08:55:46 -0700, in comp.lang.c , "hstagni"
<st****@gmail.comwrote:
>I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
This is a FAQ. - 19.1

Quick answer: you can't, C's standard IO functions all require you to
press a key to tell the programme you've finished typing.
Longer answer: your OS probably has a lower level function which can
do this. You may need to find out how to multithread your code.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 29 '07 #5
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )
>>>Why do you want that?
I am trying to convert my Pascal programs to C. But I made a Tetris
in Pascal, and the main loop of the program has a function that keeps
redrawing the screen with a delay(To make an animation) and this same
main loop reads a key from the keyboard that moves the objects on the
screen. On C, if i use getchar(), it would stop the animation and wait
for a key to be pressed: the game would suck :P
>>>>About the FAQ
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(


Mar 29 '07 #6
"hstagni" <st****@gmail.comwrites:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )
"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.

[...]
>>>>>About the FAQ
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(
Mark pointed you to question 19.1. Question 19.2 is actually more
applicable to what you're trying to do. But the conclusion is the
same: there's no way to do what you're trying to do in standard C, but
there's likely to be a system-specific way to do it (which you'll have
to ask about elsewhere).

And please learn to quote properly. The Google Groups interface does
this for you. You may find the following links useful:

http://cfaj.freeshell.org/google/
http://www.caliburn.nl/topposting.html
http://www.cpax.org.uk/prg/writings/topposting.php

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 30 '07 #7
On Mar 29, 4:58 pm, Keith Thompson <k...@mib.orgwrote:
"hstagni" <sta...@gmail.comwrites:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.
Hardly. To someone who knows C its meaning is immediately clear. Since
it's an unusual form it might take a bit longer to parse, but even if
it takes as much as an extra hundredth of a second it's not that big a
deal. To people who haven't yet got a firm grasp of C's concept of
truth, it's meaning is probably far more obvious than the idiomatic
form.

Mar 30 '07 #8
hstagni wrote:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )
>>>Why do you want that?
I am trying to convert my Pascal programs to C. But I made a Tetris
in Pascal, and the main loop of the program has a function that keeps
redrawing the screen with a delay(To make an animation) and this same
main loop reads a key from the keyboard that moves the objects on the
screen. On C, if i use getchar(), it would stop the animation and wait
for a key to be pressed: the game would suck :P
>>>>>About the FAQ
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(
<OT>
Have you looked at the NCurses howto it explains that by default it
will buffer the characters but by using raw() or cbreak() it will not
buffer the characters and send the key press directly to the program.

http://tldp.org/HOWTO/NCURSES-Progra...OWTO/init.html

There is even a code example of how to use it.
</OT>

Kind Regards,
Anthony Irwin
Mar 30 '07 #9
"J. J. Farrell" <jj*@bcs.org.ukwrites:
On Mar 29, 4:58 pm, Keith Thompson <k...@mib.orgwrote:
>"hstagni" <sta...@gmail.comwrites:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.

Hardly. To someone who knows C its meaning is immediately clear. Since
it's an unusual form it might take a bit longer to parse, but even if
it takes as much as an extra hundredth of a second it's not that big a
deal. To people who haven't yet got a firm grasp of C's concept of
truth, it's meaning is probably far more obvious than the idiomatic
form.
I should have been clearer. Someone who knows C won't scratch his
head wondering "What does that mean?". He'll more likely scratch his
head wondering "Why didn't the author just write while (1)?".

Attempting to write "while (1==1)" also creates a vulnerability to the
error of writing "while (1=1)", which is exactly what the OP initially
did.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 30 '07 #10
ma**********@pobox.com wrote:
>
What's wrong with for(;;) or while(1) ?
Is there any advantages over using a for or a while or are they
essentially the same? I know they perform the same task but is there
any technical benefits of one over the other e.g. one faster then other.

I normally use while(1) and never really considered using for(;;)
Kind Regards,
Anthony Irwin
Mar 30 '07 #11
hstagni wrote:
>
.... snip ...
>
So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(
No it didn't. It may have on your particular Pascal
implementation, using some sort of extension. Same applies to C.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Mar 30 '07 #12
On Mar 29, 6:50 pm, Keith Thompson <k...@mib.orgwrote:
"J. J. Farrell" <j...@bcs.org.ukwrites:
On Mar 29, 4:58 pm, Keith Thompson <k...@mib.orgwrote:
"hstagni" <sta...@gmail.comwrites:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )
"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.
Hardly. To someone who knows C its meaning is immediately clear. Since
it's an unusual form it might take a bit longer to parse, but even if
it takes as much as an extra hundredth of a second it's not that big a
deal. To people who haven't yet got a firm grasp of C's concept of
truth, it's meaning is probably far more obvious than the idiomatic
form.

I should have been clearer. Someone who knows C won't scratch his
head wondering "What does that mean?". He'll more likely scratch his
head wondering "Why didn't the author just write while (1)?".
If it used integer constants as in this case, and especially if it
appeared all over the code, I'd just read it as useful documentation
meaning one of two things: "the author didn't really understand
'truth' in C and might be a newbie - so watch out" or "the author is
someone who likes doing things in his own idiosyncratic ways - so
watch out".

If he were comparing a variable to itself, or if this odd construct
only occurred once among lots of "normal" cases, I would scratch my
head worrying about its being a typo.
Attempting to write "while (1==1)" also creates a vulnerability to the
error of writing "while (1=1)", which is exactly what the OP initially
did.
True, though the compiler would slap his wrist hard for that so others
shouldn't end up having to read it.

Just to be clear - I'm not advocating using this style, but I think it
accidentally gives useful clues to subsequent readers rather than
puzzling them.

Mar 30 '07 #13
Keith Thompson said:
"hstagni" <st****@gmail.comwrites:
>OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty
to me :P )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C.
I disagree. I for one consider both these forms to be aberrations rather
than idioms. The most common idiomatic ways to write a loop in C are
surely:

for(i = start; i < stop; i += inc)

and

while(conditional_expression)
"while (1==1)" will just cause your readers to scratch
their heads.
No more so than the other two.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Mar 30 '07 #14

Anthony Irwin wrote:
hstagni wrote:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :P )
>>Why do you want that?
I am trying to convert my Pascal programs to C. But I made a Tetris
in Pascal, and the main loop of the program has a function that keeps
redrawing the screen with a delay(To make an animation) and this same
main loop reads a key from the keyboard that moves the objects on the
screen. On C, if i use getchar(), it would stop the animation and wait
for a key to be pressed: the game would suck :P
>>>>About the FAQ
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(

<OT>
Have you looked at the NCurses howto it explains that by default it
will buffer the characters but by using raw() or cbreak() it will not
buffer the characters and send the key press directly to the program.

http://tldp.org/HOWTO/NCURSES-Progra...OWTO/init.html

There is even a code example of how to use it.
</OT>
But it'd still block for input, something the OP doesn't want. He
wants an asynchronous notification, on a key press.

He might have to look into signals, or as Mark McIntyre notes,
multithread his program.

Mar 30 '07 #15
On Fri, 30 Mar 2007 07:48:13 +0000, Richard Heathfield
<rj*@see.sig.invalidwrote:
>Keith Thompson said:
>"hstagni" <st****@gmail.comwrites:
>>OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty
to me :P )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C.

I disagree. I for one consider both these forms to be aberrations rather
than idioms. The most common idiomatic ways to write a loop in C are
surely:

for(i = start; i < stop; i += inc)

and

while(conditional_expression)
>"while (1==1)" will just cause your readers to scratch
their heads.

No more so than the other two.
The more conventional form of infinite loop prefix is
for ( ; ; )

--
jay
Mar 30 '07 #16
jaysome said:

<snip>
The more conventional form of infinite loop prefix is
for ( ; ; )
I consider "infinite loops" to be an aberration, not an idiom.

Your turn.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Mar 30 '07 #17
Richard Heathfield wrote:
jaysome said:

<snip>
>The more conventional form of infinite loop prefix is
for ( ; ; )

I consider "infinite loops" to be an aberration, not an idiom.
I've never seen an infinite loop, only specifications for them.

The preamble `while(1)` or `for(;;)` means, to me, "here is a
loop which C's collection of control structures doesn't give
me out of the box. Look out for some other idiom."

And the most common one of those [1] is the venerable n-and-a-half
loop:

while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

They happen often enough that I wish there were a more constrained
syntax that said that.

Now, this loop is (we hope) not infinite; does the `while(1)` trip
your abberation detectors, and what would your approach be to the
problem? [We may assume that there's no trivial function to extract
that can do the preamble-doneCondition business, on the grounds that
this is /me/, and if I though it could be done I'd already have done
it.]

[1] In my humble\\\\\\ experience.

--
Far-Fetched Hedgehog
A rock is not a fact. A rock is a rock.

Mar 30 '07 #18
Chris Dollin said:

<snip>
And the most common one of those [1] is the venerable n-and-a-half
loop:

while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

They happen often enough that I wish there were a more constrained
syntax that said that.
Yes, so do I. Nevertheless...
>
Now, this loop is (we hope) not infinite; does the `while(1)` trip
your abberation detectors, and what would your approach be to the
problem?
It does, because (in my very simplistic and naive view) while(1) is
making a promise that the break breaks, and I don't like breaking
promises if I can avoid it, so I would simply do this:

int done = 0;
while(!done)
{
preamble();
done = doneCondition();
if(!done)
{
postamble();
}
}

Yes, it's slightly more code. I don't find this to be a big deal,
although some people obviously do. Yes, it uses an extra object. I
don't find this to be a big deal, either, although some people
obviously do. But I /do/ find it to be clearer, although some people
obviously don't.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Mar 30 '07 #19
Anthony Irwin wrote:
ma**********@pobox.com wrote:
What's wrong with for(;;) or while(1) ?

Is there any advantages over using a for or a while or are they
essentially the same? I know they perform the same task but is there
any technical benefits of one over the other e.g. one faster then other.

I normally use while(1) and never really considered using for(;;)
they are funtionally identical (on any reasonable compiler).
for(;;) is a particular C idiom. Perhaps a bit "clever".
Apparently for(;;) is less likely to generate a warning.
--
Nick Keighley

Mar 30 '07 #20

"Chris Dollin" <eh@electrichedgehog.netha scritto nel messaggio
news:WJ*****************@fe1.news.blueyonder.co.uk ...
Richard Heathfield wrote:
while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}
How 'bout:
for (preamble(); !doneCondition(); preamble())
postamble();

Mar 30 '07 #21
Richard Heathfield wrote:
Chris Dollin said:

<snip>
>And the most common one of those [1] is the venerable n-and-a-half
loop:

while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

They happen often enough that I wish there were a more constrained
syntax that said that.

Yes, so do I. Nevertheless...
>>
Now, this loop is (we hope) not infinite; does the `while(1)` trip
your abberation detectors, and what would your approach be to the
problem?

It does, because (in my very simplistic and naive view) while(1) is
making a promise that the break breaks, and I don't like breaking
promises if I can avoid it, so I would simply do this:

int done = 0;
while(!done)
{
preamble();
done = doneCondition();
if(!done)
{
postamble();
}
}
/That/ trips my abomination detector. Messing around with a new
state variable, just so that `repeat A until B do C endrepeat`,
which has an idiomatic encoding using `break` can be written
without using `while(1)` ...
Yes, it's slightly more code. I don't find this to be a big deal,
although some people obviously do. Yes, it uses an extra object. I
don't find this to be a big deal, either, although some people
obviously do. But I /do/ find it to be clearer, although some people
obviously don't.
Indeed.

--
Far-Fetched Hedgehog
Notmuchhere: http://www.electrichedgehog.net/

Mar 30 '07 #22
Mark McIntyre <ma**********@spamcop.netwrote:
On 29 Mar 2007 08:55:46 -0700, in comp.lang.c , "hstagni"
<st****@gmail.comwrote:
>>I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
This is a FAQ. - 19.1
in this instance, the faq only suffers from mashing together too many
things into too few words...
Quick answer: you can't, C's standard IO functions all require you to
press a key to tell the programme you've finished typing.
Longer answer: your OS probably has a lower level function which can
do this. You may need to find out how to multithread your code.
well... the C language has no features for multithreading (a few
languages do). That's a topic for groups dealing with platforms
and configurations which support that.

However, multithreading is overkill, since (still in those other groups),
longstanding solutions used there frequently use the simpler polling
and time delay.

--
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
Mar 30 '07 #23
santosh <sa*********@gmail.comwrote:
>will buffer the characters but by using raw() or cbreak() it will not
buffer the characters and send the key press directly to the program.

http://tldp.org/HOWTO/NCURSES-Progra...OWTO/init.html

There is even a code example of how to use it.
</OT>
But it'd still block for input, something the OP doesn't want. He
wants an asynchronous notification, on a key press.
This group's faq mentions nodelay(), which does what OP asked for.
(It helps to read the corresponding manpages, since the faq does
not provide enough context to understand what is meant by its advice).

--
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
Mar 30 '07 #24
Army1987 wrote:
>
"Chris Dollin" <eh@electrichedgehog.netha scritto nel messaggio
news:WJ*****************@fe1.news.blueyonder.co.uk ...
>Richard Heathfield wrote:
while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

How 'bout:
for (preamble(); !doneCondition(); preamble())
postamble();
Only works if the ambles will fit inside the syntax of a
`for` [I often find the preamble has a declaration and I'm
not yet ready to commit to the C99 behaviour, even though
that's what's /right/].

Also writes `preamble` twice, no biscuit.

--
Ambling With Biscuits Hedgehog
Notmuchhere: http://www.electrichedgehog.net/

Mar 30 '07 #25

"Chris Dollin" <eh@electrichedgehog.netha scritto nel messaggio
news:zk****************@fe3.news.blueyonder.co.uk. ..
>> while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

How 'bout:
for (preamble(); !doneCondition(); preamble())
postamble();

Only works if the ambles will fit inside the syntax of a
`for` [I often find the preamble has a declaration and I'm
not yet ready to commit to the C99 behaviour, even though
that's what's /right/].
Anything fits inside the syntax of a for (except declarations) if you use
commas instead of colons.
Yes, if that'd mean to use twenty-five comma operators, then it is better to
write

while (1) {
twenty_five_expressions();
if (doneCondition()) break;
lotsa_expressions();
}

but then maybe it's better to split the preamble away in a new function (but
that depends on what are you doing exactly).
Mar 30 '07 #26
In article <eu**********@tdi.cu.mi.it>, Army1987 <pl********@for.itwrote:
>Anything fits inside the syntax of a for (except declarations
.... and loops, switches, ifs, ...

In fact, all you can use are expressions.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Mar 30 '07 #27
"jaysome" <ja*****@hotmail.comha scritto nel messaggio
news:iv********************************@4ax.com...
[snip]
>>"while (1==1)" will just cause your readers to scratch
their heads.

No more so than the other two.

The more conventional form of infinite loop prefix is
for ( ; ; )
C'mon. Are we going to examine an extensive corpus of C code to find out
which is more common, or what?

Somebody said that while (1==1) can be clearer than while (1) for those who
aren't accustomed to C's concept of truth. Too bad that 1 is considered to
be true in virtually all programming languages I've ever heard of. (Also, if
that is an issue, a comment saying /*endless loop*/ would do that. And both
are clearer than for(;;), as it is not obvious to everybody what an empty
second expression in the guard of a for cycle does.)

On reading "while (1==1)" I think: Why did he bother typing three more
keystrokes? Uhm... Maybe he thinks it is clearer.
On reading "for ( ; ; ) I think: Why didn't he like while (1)? Uhm... maybe
to shut off compiler warnings. (Though I'll never understand why.)
On reading "while (1)", which is the most similar to the idiomatic way to do
that in most programming languages, I just think "Intentionally infinite
loop... where does it break? Ah, here."

But they're completely equivalent. Use whichever you want, including
float temperature_of_hell = 1.4167911e32;
while (temperature_of_hell >= 273.15)

or equivalently:

int hell_freezes_over(void)
{
float temperature_of_hell = 1.4167911e32;
float freezing_temperature = 273.15
return (temperature_of_hell < freezing_temperature);
}

while (!hell_freezes_over())
Mar 30 '07 #28
Chris Dollin wrote:
Richard Heathfield wrote:
.... snip ...
>>
int done = 0;
while(!done)
{
preamble();
done = doneCondition();
if(!done)
{
postamble();
}
}

/That/ trips my abomination detector. Messing around with a new
state variable, just so that `repeat A until B do C endrepeat`,
which has an idiomatic encoding using `break` can be written
without using `while(1)` ...
Easily deabominated by:

do {
preamble();
if (!doneCondition) postamble();
else break;
} while (1);

which puts the exiting statement right up and intimately associated
with the peculiar infinity generator.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Mar 30 '07 #29
jaysome wrote:
Richard Heathfield <rj*@see.sig.invalidwrote:
>Keith Thompson said:
.... snip ...
>>>
"while (1)" and "for (;;)" are the most common idiomatic ways to
write a loop in C.

I disagree. I for one consider both these forms to be aberrations
rather than idioms. The most common idiomatic ways to write a loop
in C aresurely:

for(i = start; i < stop; i += inc)
and
while(conditional_expression)
>>"while (1==1)" will just cause your readers to scratch
their heads.

No more so than the other two.

The more conventional form of infinite loop prefix is
for ( ; ; )
Nah. You want properly self-documenting code:

infinite_loop:
.... much incomprehensible code ....
goto infinite_loop;

post_entropy_exit:
printf("The universe has ended\n");
exit(EXIT_SUCCESS);

which is uniquely marked at both ends. You can also clearly name
all your infinite loops, which is a great help during code
reviews. Note that I have used no additional vertical space as
compared to the other proposals.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Mar 30 '07 #30
Army1987 wrote:
>
"Chris Dollin" <eh@electrichedgehog.netha scritto nel messaggio
news:zk****************@fe3.news.blueyonder.co.uk. ..
>>> while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

How 'bout:
for (preamble(); !doneCondition(); preamble())
postamble();

Only works if the ambles will fit inside the syntax of a
`for` [I often find the preamble has a declaration and I'm
not yet ready to commit to the C99 behaviour, even though
that's what's /right/].

Anything fits inside the syntax of a for (except declarations) if you use
commas instead of colons.
False.

for, while, and if are obvious examples.

--
Far-Fetched Hedgehog
A rock is not a fact. A rock is a rock.

Mar 30 '07 #31
Nick Keighley wrote:
Anthony Irwin wrote:
ma**********@pobox.com wrote:
What's wrong with for(;;) or while(1) ?
Is there any advantages over using a for or a while or are they
essentially the same? I know they perform the same task but is there
any technical benefits of one over the other e.g. one faster then
other.

I normally use while(1) and never really considered using for(;;)

they are funtionally identical (on any reasonable compiler).
I also use while(1) normally.
for(;;) is a particular C idiom. Perhaps a bit "clever".
Apparently for(;;) is less likely to generate a warning.

I believe some compilers do issue a warning for the while(1) form.
Also, the for(;;) version allows the "clever" macro:

#define EVER ;;

Giving one (if one is inclined towards the "clever"):

for(EVER)
{
}


Brian
Mar 30 '07 #32
On 30 Mar 2007 16:50:37 GMT, Default User <de***********@yahoo.comwrote:
....
Also, the for(;;) version allows the "clever" macro:

#define EVER ;;

Giving one (if one is inclined towards the "clever"):

for(EVER)
{
}
Clever, but misleading.

for(EVER) {
/* ... */
/* nothing lasts forever */
break;
}

(Yes I know: "while" and "for" are also misleading, if taken
literally.)

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn!
Mar 31 '07 #33
Richard Heathfield <rj*@see.sig.invalidwrites:
jaysome said:

<snip>
The more conventional form of infinite loop prefix is
for ( ; ; )

I consider "infinite loops" to be an aberration, not an idiom.

Your turn.
When I look at "Lions' Commentary on Unix 6th Edition", and I page
through the source code to Sheet 15
....and pass my eye to main()... (line 1550)
....and let my eye read the code to line 1562.. this is what I see...

for (;;) {
UISA->r[0] = 1;
if(fuibyte(0) < 0)
break;
clearseg(i);
maxmem++;
mfree(coremap, 1, i);
i++;
}

Is this an abberration? How would you write it non-abberantly?
I am new to C and would like to learn to avoid abberant coding.

Furthermore, I am learning from K&R2, as well as...
Kernighan and Pike's "The Practice of Programming",1999

On page p12 they write:

"For an infinite loop, we prefer

for(;;)
...

but

while(1)
...
is also popular. Don't use anything other than these forms"

Again, they seem to think its an idiom; and that it should be used.

--
ilAn

>
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Mar 31 '07 #34
Jorgen Grahn wrote:
On 30 Mar 2007 16:50:37 GMT, Default User <de***********@yahoo.com>
wrote: ...
Also, the for(;;) version allows the "clever" macro:

#define EVER ;;

Giving one (if one is inclined towards the "clever"):

for(EVER)
{
}

Clever, but misleading.

for(EVER) {
/* ... */
/* nothing lasts forever */
break;
}
That's why "clever" was in scare quotes.


Brian
Apr 1 '07 #35
ilan pillemer said:
Richard Heathfield <rj*@see.sig.invalidwrites:
>>
I consider "infinite loops" to be an aberration, not an idiom.
When I look at "Lions' Commentary on Unix 6th Edition", and I page
through the source code to Sheet 15
...and pass my eye to main()... (line 1550)
...and let my eye read the code to line 1562.. this is what I see...

for (;;) {
UISA->r[0] = 1;
if(fuibyte(0) < 0)
break;
clearseg(i);
maxmem++;
mfree(coremap, 1, i);
i++;
}

Is this an abberration?
I consider it to be so, yes. It uses one C feature to defeat another.
How would you write it non-abberantly?
done = 0;
while(!done)
{
UISA->r[0] = 1;
if(!(done = fuibyte(0) < 0))
{
clearseg(i); etc etc
}
}
I am new to C and would like to learn to avoid abberant coding.
Being new to C, you should also learn that one man's aberration is
another man's feature. Opinions differ on whether broken infinite loops
are good style, and my opinion is merely that of one man.
Furthermore, I am learning from K&R2, as well as...
Kernighan and Pike's "The Practice of Programming",1999

On page p12 they write:

"For an infinite loop, we prefer

for(;;)
...

but

while(1)
...
is also popular. Don't use anything other than these forms"

Again, they seem to think its an idiom; and that it should be used.
I have to disagree with Kernighan and Pike here. I can think of only one
time where an infinite loop is a good idea, and that is the situation
where the loop is genuinely infinite (from the program's perspective).
In other words, it only stops when someone hits the big red button,
yanks out the power cord, rips out the battery, hurls the UPS out of
the window, or in some other way deprives the computer of the
continuing ability to keep the program running.

And, under those circumstances, I would select for(;;) since it avoids a
warning (e.g. "conditional expression is constant") that while(1) fails
to avoid on some compilers.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 1 '07 #36
Richard Heathfield wrote:
ilan pillemer said:
Richard Heathfield <rj*@see.sig.invalidwrites:
>
I consider "infinite loops" to be an aberration, not an idiom.
When I look at "Lions' Commentary on Unix 6th Edition", and I page
through the source code to Sheet 15
...and pass my eye to main()... (line 1550)
...and let my eye read the code to line 1562.. this is what I see...

for (;;) {
UISA->r[0] = 1;
if(fuibyte(0) < 0)
break;
clearseg(i);
maxmem++;
mfree(coremap, 1, i);
i++;
}

Is this an abberration?

I consider it to be so, yes. It uses one C feature to defeat another.
How would you write it non-abberantly?

done = 0;
while(!done)
{
UISA->r[0] = 1;
if(!(done = fuibyte(0) < 0))
{
clearseg(i); etc etc
}
}
If you want to avoid infinite loops, you could also write it as

while (UISA->r[0] = 1, fuibyte(0) >= 0) {
clearseg(i);
maxmem++;
mfree(coremap, 1, i);
i++;
}

which avoids the need for a helper variable. Personally though, I
think it's easiest read simply with for(;;).

Apr 1 '07 #37
Also, the for(;;) version allows the "clever" macro:
>
#define EVER ;;
And maybe
#define NEVER ;0;
(useful for example code which can't simplily being commented out because it
contains comments itself...)
Apr 1 '07 #38
On Apr 1, 2:43 pm, "Army1987" <please....@for.itwrote:
Also, the for(;;) version allows the "clever" macro:
#define EVER ;;

And maybe
#define NEVER ;0;
(useful for example code which can't simplily being commented out because it
contains comments itself...)
Instead of commenting out code, you can use
#if 0
/* code here */
#endif
which has the advantage of nesting.
--
ais523

Apr 1 '07 #39

"ais523" <ai****@bham.ac.ukha scritto nel messaggio
news:11**********************@p15g2000hsd.googlegr oups.com...
#define EVER ;;

And maybe
#define NEVER ;0;
(useful for example code which can't simplily being commented out because
it
contains comments itself...)

Instead of commenting out code, you can use
#if 0
/* code here */
#endif
which has the advantage of nesting.
So does

for (;0;) {
/*code here*/
}

(Which I recognize it is not the sanest way of doing that...)
Apr 1 '07 #40
Richard Heathfield <rj*@see.sig.invalidwrites:
Keith Thompson said:
>"hstagni" <st****@gmail.comwrites:
>>OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty
to me :P )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C.

I disagree. I for one consider both these forms to be aberrations rather
than idioms. The most common idiomatic ways to write a loop in C are
surely:

for(i = start; i < stop; i += inc)

and

while(conditional_expression)
[...]

Why yes, I did mean to write "infinite loop" rather than just "loop".
Kind of you to point out my error.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 1 '07 #41
Keith Thompson said:
Why yes, I did mean to write "infinite loop" rather than just "loop".
Kind of you to point out my error.
And in my own inimitable way, too. :-)

(Yeah, okay, it was a bit harsh - sorry 'bout that.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 1 '07 #42
On 30 Mar, 18:31, Chris Dollin <e...@electrichedgehog.netwrote:
Army1987 wrote:
Anything fits inside the syntax of a for (except declarations) if you use
commas instead of colons.

False.

for, while, and if are obvious examples.
You can replace for and while with recursive function calls and if
with the ternary operator. :-)

Apr 1 '07 #43
On Apr 2, 1:43 am, "Army1987" <please....@for.itwrote:
And maybe
#define NEVER ;0;
Some compilers have a bug where for(NEVER) would execute
the loop body once. That's what you get for writing such
silly code!
Apr 1 '07 #44
Old Wolf wrote:
On Apr 2, 1:43 am, "Army1987" <please....@for.itwrote:
>And maybe
#define NEVER ;0;

Some compilers have a bug where for(NEVER) would execute
the loop body once. That's what you get for writing such
silly code!

If you know a compiler that will execute..

for (;0;) puts("Nonsense");

...please tell us which. I want to avoid it.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Apr 2 '07 #45
Joe Wright wrote:
If you know a compiler that will execute..

for (;0;) puts("Nonsense");

..please tell us which. I want to avoid it.
Turbo C++ 2.0 will generate output for that. I'm not sure if this
was fixed for version 3.0.

Apr 2 '07 #46
ar******@email.it writes:
On 30 Mar, 18:31, Chris Dollin <e...@electrichedgehog.netwrote:
>Army1987 wrote:
Anything fits inside the syntax of a for (except declarations) if you use
commas instead of colons.

False.

for, while, and if are obvious examples.

You can replace for and while with recursive function calls and if
with the ternary operator. :-)
And C with Lisp.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 2 '07 #47
Old Wolf wrote:
Joe Wright wrote:
If you know a compiler that will execute..

for (;0;) puts("Nonsense");

..please tell us which. I want to avoid it.

Turbo C++ 2.0 will generate output for that. I'm not sure if this
was fixed for version 3.0.
I think even a later version of Borland's C++ implementations had this
defect. It's fixed in my 5.5 version.

Apr 2 '07 #48
"Keith Thompson" <ks***@mib.orgha scritto nel messaggio
news:ln************@nuthaus.mib.org...
ar******@email.it writes:
>On 30 Mar, 18:31, Chris Dollin <e...@electrichedgehog.netwrote:
>>Army1987 wrote:
You can replace for and while with recursive function calls and if
with the ternary operator. :-)

And C with Lisp.
Have I already told you that one of the points in my list of things to do
before dying is writing a functional-paradigm program in a language that
everybody claims to be imperative?
Apr 4 '07 #49
"Old Wolf" <ol*****@inspire.net.nzha scritto nel messaggio
news:11**********************@n59g2000hsh.googlegr oups.com...
On Apr 2, 1:43 am, "Army1987" <please....@for.itwrote:
>And maybe
#define NEVER ;0;

Some compilers have a bug where for(NEVER) would execute
the loop body once. That's what you get for writing such
silly code!
My God...

Do they work correctly if the condition is nonconstant but happens to be
false at the beginning? What if I write for (i=0; i<n; i++) printf("%d\n",
i); when n is non-positive?
Apr 4 '07 #50

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

Similar topics

1
by: Roger Godefroy | last post by:
Hi there... I want to read fieldvalues from out of a dynamicaly created table (php). But this has to be done by JavaScript. Every row of the table has a select-box, inputbox and a order-button....
1
by: Randell D. | last post by:
HELP! I am determined to stick with this... I'm getting there... for those who haven't read my earlier posts, I'm createing what should be a simple function that I can call to check that...
12
by: Anna | last post by:
Hi all, I posted the same question this afternoon but my message isn't showing up, so I thought I'd give it another try.... in case you should see it later I apologize for posting the same...
4
by: emferrari | last post by:
Hi all I need to make a program that will loop inside the HKEY_CLASSES_ROOT and find the name of the DLL associated with a ClassID. I want to know how can I possible loop inside the classes id...
15
by: Shuch | last post by:
Hi all, i m trying to read from a file and then copy it into an array...my code is as follow..it runs fine but i cant understand y it doesnt show me any output?? here is my code... using...
9
by: Eli Luong | last post by:
Hi, I have the following code below. The input file is one number/line, but the while loop is only occuring once, and it's only taking in the value of the last number (count only goes to 1 and...
0
by: samas | last post by:
I have a program that cycles through an XML file and outputs to another file every 1000 records. Thyis works fine until the end of the XML file is reached, when it fails saying my 'root' tag is not...
4
by: bmerlover | last post by:
Hi, I need to read a script file and change the text on the buttons I set. I have the psuedocode in my head, but I'm having trouble putting that into code. I figured out how to seperate B1 from T1...
5
by: sgurukrupagmailcom | last post by:
Hi, I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here: class Exc { Exc () { System.out.println ("Haribol"); }
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.