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

0 Members and 1 Guest are viewing this topic.

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #50 on: December 17, 2014, 08:17:57 pm »
By the way, what do you think of this?

char *
strcpy(char *s1, const char *s2)
{
    char *s = s1;
    while ((*s++ = *s2++) != 0)
   ;
    return (s1);
}

Perfectly readable IMHO, it's not my own style, but it's an example of what you'll see in C run time libraries everywhere.
« Last Edit: December 17, 2014, 08:21:01 pm by Howardlong »
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #51 on: December 17, 2014, 08:27:38 pm »
It's crystal clear, IMHO too, unlike the "read the code backward" cr.p, like "if (0 < foo) ...", which is horrible to read.

My 0.02$
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #52 on: December 17, 2014, 08:44:20 pm »
Yes, perhaps it's just experience, but I know the difference between = and == thank you. Not only that but your average compiler will emit an appropriate warning of it looks a bit iffy, like

if (i=0)
{
...
}

clearly is.

However unfortunately most programmers out there don't have 35+ years of experience, so if I ever deigned to go back to proper work for another mega corp who happened to have such a requirement, I would grit my teeth and get on with it. Having one op per line though, no, I think I'd graciously decline the job. Stinks of micromanagement and/or decent quality programmers either now or previously.
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #53 on: December 17, 2014, 08:54:13 pm »
Hmm, mighty glad I never worked for a large corp (other than once) that micromanaged coding to the nth degree like that. As I think I alluded to earlier, the one i did was a very large retail bank did indeed have a stipulation for only one operation in each statement, this included not being able to use

a=*p++;

It would have to be

a=*p;
p++;

My thoughts are that if everyone has to write noddy code for the lowest common denominator, it's probably time to improve that lowest common denominator. Equally, everyone must be mindful of whether they're writing write only code.

The goal is to have a uniform coding style (as in you should not be able to tell based on style who wrote what part) and get rid of silliness like writing single line ++i; instead of i++;. Common use of indents and brackets etc. It's not about producing noddy code or catering to the lowest common denominator. It's about everyone familiar with the chosen style can easily read the code and in case you leave it will be easier for someone else to take over and maintain your code.

These days it's usually automated, as in you must pass the style requirements before you can even shelve your code for a review. And usually you will have tools that will help reformat your code to pass the requirements, but as always the lazy approach is just to get it right the first time.

Back when I did real work, I wrote a spec for writing SQL statements after a number of schoolboy related coding problems. Sadly we'd had some ivory tower idiot recruited and parachuted in who was an academic with no real world experience, and demanded that everything was set-based without any procedural stuff. A noble desire. But have you ever tried to understand a ten page SQL statement with 250 tables in it? Interestingly, I was brought in when the join ended up breaking the 256 table join limit of the system when an underlying view was altered. Spent a week disecting the query and related views and re-writing it from scratch.

There is merit in trying to avoid stored procedures and functions, but really, what matters is, when your queries include joins on 100 million row tables, that you get the query execution plan right. i.e. use the best join order, the right indexes, don't pull fields you don't need etc. It's pretty bad when such queries result in large table scans. And once a heavy, cached plan, query goes wrong it will seriously affect the performance.

Analog Discovery Projects: http://www.thestuffmade.com
Youtube random project videos: https://www.youtube.com/user/TheStuffMade
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #54 on: December 17, 2014, 08:59:46 pm »
i dont see reason for not using "while" but i can see reason the why of coding style. different coding style, different purpose. i == 0 is readable (for right handed person like me) but prone to semantic error which is a nightmare. 0 == i can avoid that but its less readable. so pick your purpose, easy to debug code, or easy to read. if we know the reason, then we can be carefull and appreciate the rational when something goes upside down.

There are performant languages that don't use pointers.  I'm not sure what you mean when you say "brackets"
brackets is the [] when you try to address memory individually. i mean which is much fun typing..... a[0], a[i+1]... or *a, a++ ?. if you can enlighten me which languange other than c/c++ (or pointers capable language) that can intelligently use native machine opcode of incremental memory access, then you may have more credible claim. i mean, which languange can produce better/faster asm/machine opcode for the following code of C/C++...
Code: [Select]
int *ptr = &myArr[0], count = 2000000000;
for (int i = 0; i++; i < count) *ptr++ = 0;
or simply code another language with least amount of letters. external function call is a cheat, you should know why.

I wasn't bathed in pointers when I started programming, and therefore I don't see a need for them.  I truly don't.  I wasn't bathed in religion when I was young, either, and now I view pretty much all religion as huge wastes of time.
all you need is the will of learning new things, to be introduced and the rational behind it told to you, prejudice aside and away. once you know what and why, then you are in position of arguing of what is better or not. i agree its difficult to argue whats right and wrong since we have lack of knowledge, only the less wise people think they know all ;) but then how you are going to argue if you are not told the rationale? or the truth content about it?

i know i'm the "fixed" type person myself i resist to enter the world of "managed" language found in C# VB# hash hash thing, but i have reason for not doing so... most modern program and modern language is no better or faster, only prettier, not able to be independent without net, silverlight, the "java run in all machine" distribution or what not. just like a very good looking human, but less independent and perform poorly in bed. i stick to who perform best in bed, even not so good looking ;) keyword... functionality... beside, i can manage my own code/class/object if i want it to be prettier, thats how its done in "managed language" anyway, just behind the screen modern programmers just take it for granted and swear how prettier their app in one single line of code.
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
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #55 on: December 17, 2014, 11:12:21 pm »

There is merit in trying to avoid stored procedures and functions, but really, what matters is, when your queries include joins on 100 million row tables, that you get the query execution plan right. i.e. use the best join order, the right indexes, don't pull fields you don't need etc. It's pretty bad when such queries result in large table scans. And once a heavy, cached plan, query goes wrong it will seriously affect the performance.

It's much more than that in the SQL world. Fundamentally it's understanding the data and its distribution, then being able to read query plans, avoiding index scans as well as table scans, knowing when and how to force a plan, the effect of parameterisation, the nuances of the optimiser, undertanding IOs and spindle management to name a few. Unfortunately, in my experience of over two decades with my primarily role on SQL Server, code developers are not generally great SQL coders, but are frequently let loose.

While functionally a coder's SQL might work, you can bet your ass they won't have any clue how it will perform of a representative dataset, and will never have looked at a query plan let alone understand one. It's not their fault, it's just a specialised area, and while 95% of their SQL might work reasonably well 5% won't. I remember 15 or so years ago when the marketing mantra over databases was that the optimisers were so darned good, I almost thought I was out of a job. Actually what it meant that the edge cases were even more difficult to identify, and when they were they were a bitch to resolve. Instead it made my apparently mundane DBA job more challenging and interesting.

Anyway I digress. In general the performance thing has been my specialty for a very long time, and if I can't understand a system from the keyboard through the app, OS, network all the way through back up the server side and whatever else is going on, I would't feel qualified to make a call on a troubleshooting situation. Coder: "It's a network problem". Network guy: "It's an app problem". Server guy: "It's not the server". You must've been there. I guess it's also why I'm so at home with coding C, and, maybe once or twice a year I end up writing a bit of assembler on the very rare occasion it isn't performing quite how I wanted, and again this is a matter of understanding your data, although I debug at the machine level pretty much every day for understanding performance in embedded systems. I like my C to reflect what I think the machine's going to be doing, even though I know when I finally switch the optimiser on I can be sure under the hood it'll have generated gobbledegook.

I agree with defining certain standards like naming conventions, file locations etc but there it mostly ends for me I'm afraid. Perhaps it's because I used to define standards, but it didn't take long to discover that there were much more important battles to fight in the mega corp greasy pole than some petty layout mantra that that was more likely to make me sound anal (which I certainly am about my own code!) to the bosses than be a positive facet. As I say, if you've hired some half decent programmers they'll deal with it. If you have programmers that struggle to read and maintain reasonably written code then you've probably hired the wrong guys, maybe they should take up knitting or something.
 

Offline paulie

  • Frequent Contributor
  • **
  • !
  • Posts: 849
  • Country: us
Re: while loop in software
« Reply #56 on: December 18, 2014, 12:35:12 am »
I think the number of coders amused by this whole 0<x x>0 discussion is !0.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: while loop in software
« Reply #57 on: December 18, 2014, 12:42:57 am »
I think the number of coders amused by this whole 0<x x>0 discussion is !0.
Aaah, but is it = !0 || == !0, that the question be.

Anyways yes, the various viewpoints are amusing.  ;D And the best part is that quite a few of the opposing viewpoints are totally legit, they just depend on the environment in which said programming is intended to happen.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: while loop in software
« Reply #58 on: December 18, 2014, 01:00:29 am »
For example the use of (x<0) versus (0>x), yeah well, I'd go with (x<0) purely because this is more commonly used AND the other version has no clear advantage that I can see.

However, for the case of (lePointeurDeMerde == NULL) versus (NULL == lePointeurDeMerde) I still go with the (lePointeurDeMerde == NULL) because it's more commonly used AND I of course never ever make mistakes (ever). *ahem* But as c4757p already pointed out, the (NULL == lePointeurDeMerde) does indeed have going for it that it guards against the (NULL = lePointeurDeMerde) typo by throwing an error. This in contrast to the other version (lePointeurDeMerde = NULL) which will happily assign NULL to lePointeurDeMerde.

Now despite never ever making mistakes (ever) I have been bitten by this one in the past and it is 1) bloody annoying and 2) one of those  :palm: DOH! moments. So if that happens often enough I can readily understand the response of "ENOUGH OF THAT SHIT" and then going with the more defensive version of (NULL == lePointeurDeMerde).

Case in point, in verilog I've been bitten often enough by a simple typo in a wire name and then the synthesis tools inventing a whole new wire (the one with the typo in it). Because default nettype is wire, so there you go, a new wire with that name you just specified. What's that, your netlist is not what you intended it to be? Can't hear you over the awesomness of my DEFAULT NETTYPE. Grrr. So after you get enough of that shit 1) you become pretty good at not making that type of mistake any more, and 2) you start every frigging .v file with a `default_nettype none just so you never ever have to deal with that shit again. Luckily in systemverilog things are a lot better (yay, logic) so this kludge is no longer required. And that brings us roundtrip to C ... because we have C++ and there you also have this pass by reference thingy that reduces the amount of pointer related foot shooting. Yes yes, still pointers, but less so. Now pass by reference comes with it's own set of FUN accidents, but hey, if things worked with zero problems where would be the fun in that? :P
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2803
  • Country: nz
Re: while loop in software
« Reply #59 on: December 18, 2014, 01:40:00 am »
for ( i=0, ptr=array, bError=FALSE; i<10 && !bError; i++, ptr++)

If I was the reviewer of that code it would never make it into production or even source control. Just because you can, does not mean it's a good idea to rape a for loop.

I even demand changing simple thing like:

if (0 < x)

to

if (x > 0)

just for the sake of general easy readability. It's all about people maintaining the code in the future not wasting time because it was written by someone thinking it was cool to write in that style.

I think this is done for a valid reason that you might have overlooked.

Using '0' on the left hand side of an comparison makes it fail safe is somebody accidentally uses "=" instead of "==". You can't tell me you have never seen bugs like

Code: [Select]
  for(i = 0; i < 5; i++)
  {
     if(i = 4)
      do_something_on_last_pass()
  }

If you have the habit of making the constant on the left hand side, then the compiler will find the bug for you....

Code: [Select]
  for(i = 0; i < 5; i++)
  {
     if(4 = i)
      do_something_on_last_pass()
  }

I don't have that habit, but I respect the validity of it.
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2803
  • Country: nz
Re: while loop in software
« Reply #60 on: December 18, 2014, 01:49:45 am »
Who the hell can't easily read (0 < x)? Kindergartners? You need better colleagues...

It's all about standardizing for readability. Why would you write (NULL != MyShittyObject)? It's not like we are questioning the value of NULL or 0, so it belongs on the other side, simple as that.

Attitudes like that is the reason you will not get a Christmas bonus  8)

What would you use?  if(MyShittyObject != NULL)?, if(!MyShittyObject)?

The first is seeing if your pointer is anything other than the value defined as NULL, the second is seeing if your pointer is none-zero - and you wouldn't want to be assuming that NULL is always 0...
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #61 on: December 18, 2014, 02:18:44 am »
I think this thread is stuck in an infinite loop!
Someone please throw in a break;
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: while loop in software
« Reply #62 on: December 18, 2014, 02:22:51 am »
The real question then becomes "But how would you detect that it's stuck in an infinite loop?".

;)
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #63 on: December 18, 2014, 02:44:50 am »
By the way, what do you think of this?

char *
strcpy(char *s1, const char *s2)
{
    char *s = s1;
    while ((*s++ = *s2++) != 0)
   ;
    return (s1);
}

Perfectly readable IMHO, it's not my own style, but it's an example of what you'll see in C run time libraries everywhere.

The !=0 is redundant.
 

Offline suicidaleggroll

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
Re: while loop in software
« Reply #64 on: December 18, 2014, 03:33:57 am »
The real question then becomes "But how would you detect that it's stuck in an infinite loop?".

;)

I think three pages of posts with zero progress on the actual topic is evidence enough that it's stuck in an infinite loop.
let's see if this works...

BREAK!!!!
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: while loop in software
« Reply #65 on: December 18, 2014, 03:47:44 am »
let's see if this works...

BREAK!!!!
Nope, didn't work.

I think three pages of posts with zero progress on the actual topic is evidence enough that it's stuck in an infinite loop.
Fair enough, so lets check the OP.

Is it a bad habbit or not to use while loop in a software ?
No, it's not a bad habit. There, problem solved. BREAK?

 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #66 on: December 18, 2014, 03:48:42 am »
;

Edit, drat, won't compile, the ? and case sensitivity  :(
« Last Edit: December 18, 2014, 03:50:23 am by miguelvp »
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #67 on: December 18, 2014, 03:49:06 am »
Break? Not good enough.
Exit();
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #68 on: December 18, 2014, 05:53:21 am »
i mean, which languange can produce better/faster asm/machine opcode for the following code of C/C++...
Code: [Select]
int *ptr = &myArr[0], count = 2000000000;
for (int i = 0; i++; i < count) *ptr++ = 0;

There are several that (at my last measure) get close enough in speed to C that there is no clear winner.

That is, if you're only talking about walking an array.  If you're talking about writing over in-use RAM with zeroes, well, you got me there.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #69 on: December 18, 2014, 06:15:07 am »
Break? Not good enough.
Exit();

Should be:

exit();

but:

Code: [Select]
void exitFunction()
{
   for(;;);
}

int main ()
{
   int getout = 0;
   atexit(exitFunction);

   for(;;) {
      ... // something triggers getout to be 1.
      if(getout) {
         exit();
      }
   }
}

Of course break; won't help in this case either :)
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #70 on: December 18, 2014, 06:23:13 am »
Getting back to the original question...
I don't think I've ever heard anyone claim that "while loops" should be avoided.  AFAIK, they're still considered one of the basic control structures.

In C, there's a specific and relatively common variation of a while loop that gets a fair amount of bad press:
Code: [Select]
while (c = getchar()) { ...but the complaint is the combination of assignment/conditionalism, rather than the loop itself.

In some of your "newer" languages (python, perl, java) have "list" data structures that can be iterated directly (usually with a "for" statement of sometime) and I can imagine that there is some pressure to use those rather than more primitive types with more primitive loops.  Loops where you calculate endpoints instead of having the compiler derive them directly from the data are more prone to errors.

 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #71 on: December 18, 2014, 06:26:28 am »
i mean, which languange can produce better/faster asm/machine opcode for the following code of C/C++...
Code: [Select]
int *ptr = &myArr[0], count = 2000000000;
for (int i = 0; i++; i < count) *ptr++ = 0;

There are several that (at my last measure) get close enough in speed to C that there is no clear winner.

That is, if you're only talking about walking an array.  If you're talking about writing over in-use RAM with zeroes, well, you got me there.

inlined memset is probably your faster memory clear implementation other than targeting the actual processor in assembly and the gain might not be much if any at all.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #72 on: December 18, 2014, 07:19:23 am »
By the way, what do you think of this?

char *
strcpy(char *s1, const char *s2)
{
    char *s = s1;
    while ((*s++ = *s2++) != 0)
   ;
    return (s1);
}

Perfectly readable IMHO, it's not my own style, but it's an example of what you'll see in C run time libraries everywhere.

The !=0 is redundant.

LOL! That'll upset someone!

Seriously speaking, in that case personally speaking I include the comparison explicitly for clarity, it makes no difference to the code generated, and any half decent compiler these days would throw up a warning without it if I didn't. We do all leave warnings on now, don't we?!?!

But what I don't do is...

while (bRunning == TRUE)
...or...
while (bFinished == FALSE)

Instead I do

while (bRunning)
...or...
while (!bFinished)

I did work at a place where we had to do the former about twenty five years ago. The coding "standards" boss there was from a Foxpro background, he didn't understand what a boolean was. This was the same guy who, to really confuse things, got the 1s and 0s mixed up half the time anyway, so for some variables a true would be zero and some it would be one. A great guy down the pub, but not really cut out as a programmer. This was in a mega corp, by the way.

Subnote about warnings: I wrote some open source code for Qt a few years ago, it compiled fine, at the time. It also used another open source third party cross platform USB HID library. Roll on two years later, Qt had moved on and the third party library now generated half a dozen compiler warnings. I had some guy rant at me in a snotogram about how shitty the (free open source) code was because of that. He assumed that it also threw up warnings when I'd compiled it two years earlier, which it hadn't. (This is a problem for Qt in my experience, obtaining and successfully installing older toolchains seems not to be so simple, makes maintenance a nightmare).

 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #73 on: December 18, 2014, 08:48:20 am »
The !=0 is redundant.
No, it's good coding style. Several coding conventions demand this. Languages like Java wouldn't even compile the code if the condition wasn't boolean.
Letting aside that an assignment inside a condition is also something that wouldn't pass any code review.
People tend to think that shorter C code always creates shorter/faster ASM code. This is an invalid assumption in many cases though.
Trying is the first step towards failure - Homer J. Simpson
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #74 on: December 18, 2014, 09:23:05 am »
i mean, which languange can produce better/faster asm/machine opcode for the following code of C/C++...
Code: [Select]
int *ptr = &myArr[0], count = 2000000000;
for (int i = 0; i++; i < count) *ptr++ = 0;
There are several that (at my last measure) get close enough in speed to C that there is no clear winner.
That is, if you're only talking about walking an array.  If you're talking about writing over in-use RAM with zeroes, well, you got me there.
inlined memset is probably your faster memory clear implementation other than targeting the actual processor in assembly and the gain might not be much if any at all.
that is in its simplistic form and the dumbest example ever... we know zeroing memory using memset or other built in function... please redo again with....
Code: [Select]
int *ptr = &myArr[0], count = 2000000000;
for (int i = 0; i++; i < count) *ptr++ = (some inline very complex or cryptic mathematical formula)(i,x,y,etc);
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
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf