Author Topic: while loop in software  (Read 64853 times)

0 Members and 1 Guest are viewing this topic.

Offline old greggTopic starter

  • Regular Contributor
  • *
  • Posts: 130
  • Country: 00
while loop in software
« on: December 16, 2014, 05:49:39 pm »
Is it a bad habbit or not to use while loop in a software ?

I vaguely remember hearing it in a course that I was watching on youtube.

What's the general idea of it ?


« Last Edit: December 16, 2014, 06:02:28 pm by old gregg »
 

Offline Wilksey

  • Super Contributor
  • ***
  • Posts: 1329
Re: while loop in software
« Reply #1 on: December 16, 2014, 06:17:25 pm »
Depends what you're writing.

In micros typically you will have a while loop in your main() after you have set everything up i.e., interrupts etc, as you never want that to end.

You can use while loops in something like threads under PC based programming for a RX handler for serial comms for example, make sure you have a mechanism to kill the thread though at program termination.

In a standard application, yes, it's a bad idea as you will just hang the system unless you yield processor execution to another thread.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 19195
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: while loop in software
« Reply #2 on: December 16, 2014, 06:24:20 pm »
Is it a bad habbit or not to use while loop in a software ?

I vaguely remember hearing it in a course that I was watching on youtube.

What's the general idea of it ?

You have a very bad habit. You should goto instead :)
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #3 on: December 16, 2014, 06:40:46 pm »
A while loop is more susceptable to programmer error due to the fact that it often relies on external variables. And if while never becomes false, your app will hang.

In event-driven graphical applications, such as Qt or C#, using a long or stuck while loop prevents the user interface from being refreshed and parsed for new events. Resulting in the world famous Windows title bar: "MyProgram (not responding)". It is better to avoid a while loop in such cases.
Same goes for a string termination finder using a While. What happens when the string isn't terminated due to an rs232 bit error? Is it going to walk through the memory?

However, a while(i--) loop is usually faster than a for(i=0; i<x; i++) loop. Leaving much room for debate, per use-case, software design and compiler + settings.

 

Offline Neilm

  • Super Contributor
  • ***
  • Posts: 1545
  • Country: gb
Re: while loop in software
« Reply #4 on: December 16, 2014, 06:44:25 pm »
A while loop is all too easy to end up with an infinite loop. There are only a few times I would ever use one. The most obvious one I have encountered - embedded systems that are just running a simple programme - while{1} for the main programme loop.
Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe. - Albert Einstein
Tesla referral code https://ts.la/neil53539
 

Offline AG6QR

  • Frequent Contributor
  • **
  • Posts: 857
  • Country: us
    • AG6QR Blog
Re: while loop in software
« Reply #5 on: December 16, 2014, 06:53:37 pm »
It has its pitfalls, but I've never seen a nontrivial program that doesn't have a while loop in it somewhere.  (OK, I have seen nontrivial programs written in assembler and in FORTRAN 66, languages which don't support "while" explicitly, but nontrivial programs in those kinds of languages generally emulate the "while" construct using conditional gotos somewhere.)

The biggest pitfall is that it's up to the programmer to ensure the terminating condition will eventually be met.  A while can unintentionally become an infinite loop.
 

Offline jeremy

  • Super Contributor
  • ***
  • Posts: 1079
  • Country: au
Re: while loop in software
« Reply #6 on: December 16, 2014, 06:54:25 pm »
I'm going to have to be that guy, and say that I use them fairly often. How about something like

Code: [Select]
while (c = stream.getc()) { ... process c ... }
You will often find code like this in places that are constrained by non-deterministic or blocking behaviour, as you cannot predict when the loop will end.

I also very often use
 
Code: [Select]
while(chip_is_busy);
because while it serves its purpose of waiting until the chip isn't busy, when you attach a debugger it shows you the exact failure point.

Of course, I would never use a while loop where a for loop is appropriate though.

I think the problem of random, cosmic-ray/transient silicon bug induced infinite loops is mostly sorted by watchdog timers.
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #7 on: December 16, 2014, 06:55:04 pm »
A while loop is all too easy to end up with an infinite loop. There are only a few times I would ever use one. The most obvious one I have encountered - embedded systems that are just running a simple programme - while{1} for the main programme loop.
And your compiler didn,t throw an error? Change compiler while(1) your at it ;)
 

Offline mazurov

  • Frequent Contributor
  • **
  • Posts: 524
  • Country: us
Re: while loop in software
« Reply #8 on: December 16, 2014, 07:50:26 pm »
Every feature of well-designed language can be efficiently used under certain conditions and any advice which fits 'avoid x' pattern should be ignored, if one desires to become better programmer. 
With sufficient thrust, pigs fly just fine - RFC1925
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #9 on: December 16, 2014, 07:56:33 pm »
Every feature of well-designed language can be efficiently used under certain conditions.
Problem solved.

Lets not forget about While's brother, do{ ... }while();
Which might help you preventing these rare statements: "while(c = stream.getc())".
 

Offline 22swg

  • Frequent Contributor
  • **
  • Posts: 274
  • Country: gb
Re: while loop in software
« Reply #10 on: December 16, 2014, 08:38:27 pm »
My C is that of a 4 Year old  :D , so loads of while(  :-[ ) loops..... But on entering the function i do set a marker flag and reset the watchdog timer , if loop becomes too long , WD interrupt code sorts out the loop, either retry or whatever for that code, while coding I2C from scratch I found I had a forest of while(s) but WD solved timeouts.  ( PIC24F embeded )     
Check your tongue, your belly and your lust. Better to enjoy someone else’s madness.
 

Offline mazurov

  • Frequent Contributor
  • **
  • Posts: 524
  • Country: us
Re: while loop in software
« Reply #11 on: December 16, 2014, 08:53:21 pm »
Which might help you preventing these rare statements: "while(c = stream.getc())".

Random data like that will be much better handled by event-driven code, i.e., a received character or a string would generate an event passing the data to the object that will process it. This, however, requires the program to be designed first and only then written into code. Also, the code size will increase.

On the other hand, I sometimes write programs for tiny Microchip 10F MCUs (available in 5-pin SOT, highly recommended). The program often fits on 3-4 screens, including configuration bits.  Such program can be coded in any way imaginable as long as it works.
With sufficient thrust, pigs fly just fine - RFC1925
 

Offline suicidaleggroll

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
Re: while loop in software
« Reply #12 on: December 16, 2014, 09:01:32 pm »
any advice which fits 'avoid x' pattern should be ignored, if one desires to become better programmer.
I disagree.  There are certain features of certain languages that should be avoided like the plague, simply because they are nothing but a shortcut for the original developer that makes debugging more difficult for absolutely no benefit.

A quick example is implicit variable declaration in Fortran.  Using implicit declaration does not make you a better programmer, it makes you a lazy programmer, and anybody else trying to use the code will curse your name until somebody fixes it.  Same goes for using common blocks instead of passing variables between functions, goto/label, etc.

A while loop does not fit into that category though, it has its place.
 

Offline macboy

  • Super Contributor
  • ***
  • Posts: 2250
  • Country: ca
Re: while loop in software
« Reply #13 on: December 16, 2014, 09:12:21 pm »
...I also very often use
 
Code: [Select]
while(chip_is_busy);...
I would never do this. I would never let code like that past a code inspection.
You need to have a timeout in order to prevent the possibility that a hardware failure or glitch can bring the software to a grinding halt.
 

Offline Seekonk

  • Super Contributor
  • ***
  • Posts: 1938
  • Country: us
Re: while loop in software
« Reply #14 on: December 16, 2014, 09:30:37 pm »
Elsewhere I have attempted to get people to use small controllers like the UNO to solve simple control problems.  I tell them to use nothing but a simple one line IF statement.    Every line of code should stand on its own.  I don't want to get married to these peoples problems.
 

Offline mazurov

  • Frequent Contributor
  • **
  • Posts: 524
  • Country: us
Re: while loop in software
« Reply #15 on: December 16, 2014, 10:00:54 pm »
any advice which fits 'avoid x' pattern should be ignored, if one desires to become better programmer.
I disagree.  There are certain features of certain languages that should be avoided like the plague

You missed 'well-designed' clause. FORTRAN has been developed very early and is quite crude comparing to even K&R C dialect. Coders of my age still smile at "you can write FORTRAN programs in any language" joke. If you want my opinion, the whole FORTRAN should be avoided (which is not that difficult nowadays).
With sufficient thrust, pigs fly just fine - RFC1925
 

Offline AG6QR

  • Frequent Contributor
  • **
  • Posts: 857
  • Country: us
    • AG6QR Blog
Re: while loop in software
« Reply #16 on: December 16, 2014, 10:54:00 pm »
It may be worth noting that a for loop in C/C++ is compiled as a while loop.

That is, the block
Code: [Select]
for (s1; s2; s3) {
  ...body...
}

is compiled exactly as

Code: [Select]
s1;
while(s2) {
   {
      ...body...
   }
   s3;
}

So if the person you're working for has some crazy rule that forbids you from writing while loops, and you write

Code: [Select]
while (a < b) {
   xyz();
}

you could always rewrite it as

Code: [Select]
for(;a < b;) {
   xyz();
}

That would meet the letter, but probably not the spirit, of the prohibition against while loops.

Maybe a more important point here is that, in C/C++, for loops are not guaranteed to terminate.  Sure, by choosing appropriate initialization, test, and increment statements, you can guarantee termination, with a "for" or a "while", but you can make either kind of loop go infinite, too.  There are languages which have iterative loops that are always guaranteed to terminate, but C/C++ is not one of those languages.

Finally, guaranteed termination isn't always a panacea.  The following ugly FORTRAN 66 code is guaranteed to terminate, but not necessarily before the Sun enters its red giant phase and engulfs the Earth.

Code: [Select]
      DO 10 I = 1, 1000000
      DO 10 J = 1, 1000000
      DO 10 K = 1, 1000000
      DO 10 L = 1, 1000000
      DO 10 M = 1, 1000000
      DO 10 N = 1, 1000000
      DO 10 II = 1, 1000000
      DO 10 JJ = 1, 1000000
      DO 10 KK = 1, 1000000
10    CONTINUE
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #17 on: December 16, 2014, 11:13:44 pm »
Of all the things people are afraid of, while loops? Are you kidding me? :scared:
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #18 on: December 17, 2014, 03:23:40 am »
It may be worth noting that a for loop in C/C++ is compiled as a while loop.

That is, the block
Code: [Select]
for (s1; s2; s3) {
  ...body...
}

is compiled exactly as

Code: [Select]
s1;
while(s2) {
   {
      ...body...
   }
   s3;
}


This doesn't look right because a 'continue' in the body will skip s3.

OP, nothing wrong with using while or do-while loops. Personally I find that in most cases for( ; ; ) does the trick for me. Note that three expression of within the for( ; ; ) are optional.
 

Offline mazurov

  • Frequent Contributor
  • **
  • Posts: 524
  • Country: us
Re: while loop in software
« Reply #19 on: December 17, 2014, 04:47:06 am »
Of all the things people are afraid of, while loops? Are you kidding me? :scared:

I felt the same way when people became afraid of pointers. It was long time ago and special languages has been developed for said people, but even today I have an occasional conversation with a fan of "pointer-less"  design of a C program.
With sufficient thrust, pigs fly just fine - RFC1925
 

Offline Sal Ammoniac

  • Super Contributor
  • ***
  • Posts: 1660
  • Country: us
Re: while loop in software
« Reply #20 on: December 17, 2014, 06:07:58 am »
There's nothing wrong with while loops. Every embedded application I've ever written as had at least one while(1) {} loop in it.
Complexity is the number-one enemy of high-quality code.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #21 on: December 17, 2014, 07:52:13 am »
Is it a bad habbit or not to use while loop in a software ?
I vaguely remember hearing it in a course that I was watching on youtube.
forget the naysayers. use it to your heart content, use it all. what? i heard "goto" is not suppose to. GTFO, as long as my program is working. if you forget and infinite loop or whatever, dont blame the language, learn how to blame yourself.

What's the general idea of it ?
thay want to show the world that they are better or cleverer than the languange inventor who placed the while(1), for(;; ) in the first place. we engineer, we dont "not use" stuffs provided to us to solve problems.
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline grumpydoc

  • Super Contributor
  • ***
  • Posts: 2905
  • Country: gb
Re: while loop in software
« Reply #22 on: December 17, 2014, 08:09:26 am »
Quote
This doesn't look right because a 'continue' in the body will skip s3.
True, it's the example given in most text books though and is equivalent in the absence of "continue"

The upshot is that you can use a for loop to construct a while loop, but not always the other way round
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #23 on: December 17, 2014, 09:48:01 am »
I use while very frequently, but it's rare that I use do ... while, not because I don't want to, but because my own style doesn't need it.

My own style is to avoid goto at all costs, and almost to the same degree the use of continue or break within any loop, favouring instead setting a boolean for testing in the while clause. It might be a bit more wordy, but it makes more sense to me that way. I honestly cannot remember the last time I used a goto, althouh ISTR some of the IBM and Microsoft OS/2 API examples used it for error conditions.

The same applies to the use of return in the middle of a function, even in an error condition. I use a boolean instead. It's all down to maintaining flow and avoiding spaghetti code.

It's not all the time, but equally it's not uncommon for me to put in multiple assignments, comparisons and iterators in for(;;) terminations, typically a boolean again that, for example, traps an error condition. About 20 years ago I worked on a large retails banking system where this was banned, because it too easily makes for write-only code. While I understand this, as long as it's well laid out and there's no obfuscation, it can often make perfect logical sense to put, say,

 for ( i=0, ptr=array, bError=FALSE; i<10 && !bError; i++, ptr++)

however I'd say that example is pretty extreme for me, and I'd probably be already initialising at least so e of the variables elsewhere anyway, such as at declaration time.

One further thing, I frequently have a volatile NOP in an otherwise empty loop. This is so I can easily put a breakpoint inside the loop if necessary. It's volatile so it doesn't get optimised away.

But a blanket ban on while is a bit silly IMNSHO.
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #24 on: December 17, 2014, 10:33:09 am »
for ( i=0, ptr=array, bError=FALSE; i<10 && !bError; i++, ptr++)
Programming like this makes me want to kick the colleague that wrote it.
Code should be unambiguous clearly written most in short one liners and as much comment as is needed to understand the code 3 years later without RTFD.
I am often confronted to add code to old code and if you stick to the don't be too smart for your own good programming this is a piece of cake.
If you are a programmer that gets a kick out of reducing 50 easy to understand loc's to 5 extremely difficult loc's than do so for your own hobby but please not for a commercial release. Sorry made me rant , I once had a PhD dump his C code on me to put in a product and the longest variable name he used was "xts"  :scared:
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf