Author Topic: while loop in software  (Read 64854 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:
 

Offline jeremy

  • Super Contributor
  • ***
  • Posts: 1079
  • Country: au
Re: while loop in software
« Reply #25 on: December 17, 2014, 11:32:32 am »
...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.

To be fair, I was talking about using this code in debugging so that you could attach a debugger...
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #26 on: December 17, 2014, 11:55:15 am »
...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.

From that tiny bit of code, how can you tell that there isn't a separate thread that handles a timeout condition (e.g. an interrupt) ?
 

Offline dannyf

  • Super Contributor
  • ***
  • Posts: 8221
  • Country: 00
Re: while loop in software
« Reply #27 on: December 17, 2014, 11:57:51 am »
Quote
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.

Agreed. A piece of code that's not readable is not a maintainable thus not usable. Such code can be very dangerous and is a cost item, rather than investment in any organization.

The same goes with

Code: [Select]
while (condition is true);
================================
https://dannyelectronics.wordpress.com/
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #28 on: December 17, 2014, 12:02:30 pm »
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.

+1

Code should be simple and straight forward.
 

Offline ptricks

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: us
Re: while loop in software
« Reply #29 on: December 17, 2014, 12:19:28 pm »
I use
while(1);

quite a bit when I want to stop a program from moving to the next step but don't have debug options.
 

Offline grumpydoc

  • Super Contributor
  • ***
  • Posts: 2905
  • Country: gb
Re: while loop in software
« Reply #30 on: December 17, 2014, 12:28:32 pm »
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 have to say I don't have too much of a problem with that for loop, it's a little full but easy to see what's going on.

I do have a bit of an issue with the mixture of Hungarian and non-Hungarian notation though. I'm no big fan of Hungarian but if you are going to use it do so consistently.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #31 on: December 17, 2014, 03:27:14 pm »
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.

Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.

I still don't see the need for the effing things.

I think some people just really like to put little stars by all their variable names.
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #32 on: December 17, 2014, 04:16:28 pm »
Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.
I still don't see the need for the effing things.
I wonder how you will write a messageprotocol handler without using pointers or any large structure with multiple data stuffed behind eachother.
All you can do is handle elementary datatypes.
I will go as far as say that you can not write a serious c program without any pointers.
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #33 on: December 17, 2014, 04:54:40 pm »
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.

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 #34 on: December 17, 2014, 05:54:54 pm »
I still don't see the need for the effing things.
dynamically created memory, polymorphism to name a few...
I think some people just really like to put little stars by all their variable names.
and performance for eternity. well star is better than brackets isnt it?
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 jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #35 on: December 17, 2014, 05:55:12 pm »
Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.

I still don't see the need for the effing things.

I think some people just really like to put little stars by all their variable names.


Pointers can be confusing, especially when you have pointers to arrays of pointers pointing to object containing pointers or linked lists of pointers etc.

But explicit pointers in languages like c and c++ do give you more control (and understanding of the actual implementation) than implicit pointers in languages like c# where you need to differentiate between value and reference types. E.g. trying to expose a writable variable in a structure in c# through a class property is not possible. That can be very confusing to a dev lacking understanding of the pointer concepts.

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

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #36 on: December 17, 2014, 06:01:42 pm »
I even demand changing simple thing like:

if (0 < x)

to

if (x > 0)

just for the sake of general easy readability.

Who the hell can't easily read (0 < x)? Kindergartners? You need better colleagues...
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #37 on: December 17, 2014, 06:11:43 pm »
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)

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

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #38 on: December 17, 2014, 06:20:23 pm »
Why would you write (NULL != MyShittyObject)?

Habit, from writing (NULL == MyShittyObject). I've heard rather convincing arguments in favor of preferring that approach so that an accidental (NULL = MyShittyObject) becomes invalid code.

Looks quite readable to me, too. Perhaps some people need to spend their Christmas bonuses on reading glasses? >:D
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #39 on: December 17, 2014, 06:31:39 pm »
Habit, from writing (NULL == MyShittyObject). I've heard rather convincing arguments in favor of preferring that approach so that an accidental (NULL = MyShittyObject) becomes invalid code.

Looks quite readable to me, too. Perhaps some people need to spend their Christmas bonuses on reading glasses? >:D

Let's just say you'd have a tough time in my team :) I don't have much patience for "enlightened" individuals with arguments like: because reasons.

Working against the general consensus never brought good results unless you have convincing arguments why your style is superior.

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

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #40 on: December 17, 2014, 06:38:39 pm »
Let's just say you'd have a tough time in my team :)

A team whose leader quibbles about things like which side of the comparison operator the constant goes on? I daresay I would. But that sort of ridiculous, overreaching micromanagement is rampant in software anyway - I'm quite glad to be out of it. :phew:

Working against the general consensus

You've an amusing understanding of "consensus".
No longer active here - try the IRC channel if you just can't be without me :)
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #41 on: December 17, 2014, 06:45:40 pm »
Who the hell can't easily read (0 < x)? Kindergartners? You need better colleagues...
It becomes much harder when you have (0 < someFunctionWithArguments(&argument, with, value, DEFINE))
But the psuedo doesn't make sense. You want the result of this() to be higher than 0. Not zero to be lower than the result of this().
It isn't rare to have style rules. http://www.chibios.org/dokuwiki/doku.php?id=chibios:guides:style_guide
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #42 on: December 17, 2014, 06:46:22 pm »
A team whose leader quibbles about things like which side of the comparison operator the constant goes on? I daresay I would. But that sort of ridiculous, overreaching micromanagement is rampant in software anyway - I'm quite glad to be out of it. :phew:

You've an amusing understanding of "consensus".

Clearly you've never spent time in a shiproom evaluating and triaging stupid bugs by "enlightened" developers trying to get a product ready to ship.

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

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #43 on: December 17, 2014, 06:55:30 pm »
It becomes much harder when you have (0 < someFunctionWithArguments(&argument, with, value, DEFINE))

...it does? Funny, I just picture a number line. 0 is here... and sFWA(...) is here. Rather in the order they were written, actually.

Flip it around and I have to picture that line backwards. Makes me have to stop and reconsider the code in a different way.

Face it, different people think in different ways, and you two just happen to be arrogant enough to think your way is how everybody thinks. Some people will find your way easier, and others will find it harder. All you're doing is choosing a half of your devs to make uncomfortable. I wonder how much crap code that makes them churn out...

Quote
You want the result of this() to be higher than 0. Not zero to be lower than the result of this().

The two are exactly equivalent - I want both!

Quote
It isn't rare to have style rules. http://www.chibios.org/dokuwiki/doku.php?id=chibios:guides:style_guide

It isn't rare for those style rules to be batshit insane either. Like this:

Quote
Very important types are allowed to be use camel case. Less important types must be all lower case and suffixed by a “_t”.

Very important types? What the hell are those? The ones with an MBA?

Clearly you've never spent time in a shiproom evaluating and triaging stupid bugs by "enlightened" developers trying to get a product ready to ship.

And you think demanding they put the constant on the "correct" side of the comparison operator will improve them? They're just shitty devs with big egos! You'll never improve them.
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline baljemmett

  • Supporter
  • ****
  • Posts: 665
  • Country: gb
Re: while loop in software
« Reply #44 on: December 17, 2014, 07:04:16 pm »
Habit, from writing (NULL == MyShittyObject). I've heard rather convincing arguments in favor of preferring that approach so that an accidental (NULL = MyShittyObject) becomes invalid code.

Let's just say you'd have a tough time in my team :) I don't have much patience for "enlightened" individuals with arguments like: because reasons.

Except he gave you a reason...  Of course, you can think that said reason isn't good enough for you, and your style guide is free to say whatever it wants, but to sarcastically characterise someone else's justified argument as an "enlightened" equivalent of "because reasons" puts you squarely in the category you claim not to have time for.
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #45 on: December 17, 2014, 07:11:23 pm »
Let's leave it here I don't think we are getting anywhere.

But if you ever get a real job with a large corp, you might be surprised to find there are strict standards and unless you comply, your work will be rejected.

I do believe you can see the benefits and logic in adhering to a standardized style opposed to everyone exercising individual styles.

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

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #46 on: December 17, 2014, 07:46:30 pm »
Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.
I still don't see the need for the effing things.
I wonder how you will write a messageprotocol handler without using pointers or any large structure with multiple data stuffed behind eachother.
All you can do is handle elementary datatypes.
I will go as far as say that you can not write a serious c program without any pointers.

Your last sentence sums it up, for me.  Except, I read it as "avoid C whenever possible."  I misspoke a bit; I don't mean "write C without pointers," I mean "DON'T WRITE USING C."  Use C++ at least.  It's a lot less stupid than C, you can get object orientation and provide SOME structure to your application.

I'm NOT advocating ANY other language, I'm not bashing C in favor of [insert language], I just hate pointers.  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.

You're free to disagree with me, if you like.  I'm not going to tell you you're wrong, because I don't know that you're wrong, or that I'm right.  It's just what I think.

I still don't see the need for the effing things.
dynamically created memory, polymorphism to name a few...
I think some people just really like to put little stars by all their variable names.
and performance for eternity. well star is better than brackets isnt it?

There are performant languages that don't use pointers.  I'm not sure what you mean when you say "brackets" because that term seems to vary between countries, but I will say that the only time I use * or & voluntarily, they are used as operators and not pointers.
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #47 on: December 17, 2014, 07:53:10 pm »
Not important who is right or wrong thats too black/white but I can not see even writing C++ without pointers, i mean do you use structs? Will you pass them by value or by reference in a function? If by value please do not write embedded code it will eat your stack for lunch if that computes ????
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #48 on: December 17, 2014, 08:07:55 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++;

However, bearing in mind the quality of the programmers they were using, basically new graduates dropped in there by a very large accountant with an IT consultancy bolted on the side, it needed to be simple.

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.

Regarding not using pointers, I'd say that it's probably more to do with not being comfortable with the concept rather than being bad. In embedded stuff and driver programming in particular, where performance is everything, pointers bring you closer to the machine code. Passing data structures by value ain't going to win you any races.

About the mix of Hungarian and non-Hungarian, somewhat ironically I was trying to give a clear example without a ton of other code. From the comments, like it or not it appears it succeeded in doing that, in fact it seems that everyone knew what was being done in at statement. Although I wouldn't go to those extremes in practice, it seems it was clear in what was being attempted. BTW, no, I don't mix, I'm pretty anal about the style and consistency that I use, and like it or not I was brought up on Hungarian and have no intention of changing now!

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.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #49 on: December 17, 2014, 08:11:07 pm »
Not important who is right or wrong thats too black/white but I can not see even writing C++ without pointers, i mean do you use structs? Will you pass them by value or by reference in a function? If by value please do not write embedded code it will eat your stack for lunch if that computes ????

With c++ you don't need a pointer to pass by reference.
 

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
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #75 on: December 18, 2014, 09:41:23 am »
You just need to call:

 memset(myArr, 0, 2000000000*sizeof(int));

And you are done.

If the micro has a set repeat and loop instruction set it will use that, using the for loop won't give enough hints to the compiler to choose a single assembly instruction.

Look up Single Instruction Multiple Data (SIMD)

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

Oh since I'm simple and dumb, you should revisit your understanding on how a for loop is constructed, since your loop wont even do one iteration :P

I guess your code is faster since it doesn't change anything in memory  :-DD
« Last Edit: December 18, 2014, 09:44:40 am by miguelvp »
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #76 on: December 18, 2014, 10:03:32 am »
Also, I would use size_t for "i"  ;-)
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #77 on: December 18, 2014, 10:23:53 am »
Also, I would use size_t for "i"  ;-)

Someone will just come along and point out that signed-vs-unsigned is just too confusing for their terrible developers...
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline AndreasF

  • Frequent Contributor
  • **
  • Posts: 251
  • Country: gb
    • mind-dump.net
Re: while loop in software
« Reply #78 on: December 18, 2014, 10:42:33 am »
I also think while loops are perfectly acceptable and useful, and in some languages may even be required to solve a particular problem. I got bitten by this in Matlab a while back when I foolishly assumed that a Matlab "for x=1:1:100" is equivalent to "for(int x=1; x<101, x++)". Try this to see why:

Code: [Select]
for x=1:10,
if (x>5), x=x+1; end;
disp(x);
end

my random ramblings mind-dump.net
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #79 on: December 18, 2014, 10:49:52 am »
Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.
I still don't see the need for the effing things.

If you were designing a language, and someone wants to pass a huge structure or array between functions, how would you achieve this?  Would you copy this enormous data structure onto the stack, massively slowing program execution and greatly increasing memory requirements, or would you pass a reference?  Undoubtedly you would choose the latter in nearly all circumstances.  Passing by reference is using a pointer, even though it may be done "under the hood".

A major part of the power of C is the ability to explicitly use and manipulate pointers, and they are absolutely nothing to be afraid of once you learn to use them correctly.  Suggesting C should be avoided because it uses pointers is like saying cars should be avoided because they use wheels.
« Last Edit: December 19, 2014, 09:53:36 pm by mikerj »
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #80 on: December 18, 2014, 11:18:34 am »
Also, I would use size_t for "i"  ;-)

Someone will just come along and point out that signed-vs-unsigned is just too confusing for their terrible developers...

I'm afraid count assignment will make the compiler unhappy ;-)
 

Online gmb42

  • Frequent Contributor
  • **
  • Posts: 294
  • Country: gb
Re: while loop in software
« Reply #81 on: December 18, 2014, 11:45:02 am »
Hard to say these days what the result of any C statement will be, even a simple for loop may well be optimised.

For instance, the latest Visual Studio compilers (VS2012 on) when compiling for PC will vectorise a for loop, if the count is upwards and the step size is 1.  This means I have to get out of the habit of 30 years of making for loops count down to zero to save a comparison with the terminal value.

 

Offline AndyC_772

  • Super Contributor
  • ***
  • Posts: 4206
  • Country: gb
  • Professional design engineer
    • Cawte Engineering | Reliable Electronics
Re: while loop in software
« Reply #82 on: December 18, 2014, 12:01:34 pm »
Would someone mind please explaining what they think should be used instead of a while{} loop, and why the alternative is better?

Surely a perfectly good, generic solution to the "problem" of the loop never terminating, is to write code of the form:

while ((condition is true) && (there is still likelihood that condition will become false at some point in the future))
{
  do stuff that affects condition;
  check that it's still reasonable to be looping;
}

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #83 on: December 18, 2014, 12:28:13 pm »
Would someone mind please explaining what they think should be used instead of a while{} loop, and why the alternative is better?

Quite.  It's as daft as suggesting people should avoid using pointers at all costs.
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #84 on: December 18, 2014, 12:48:45 pm »
while() / do while()

There's nothing wrong with while() and some programmers consider it more elegant. Use what you think fits best. I use while() more often than for(), because the variable/counter handling is more visible to me, expecially in complex loops.

code conventions

We all should have some, not just for teams but also for one-man projects. It makes maintenance much more easy. If you work on code from someone else or some of your own old code you'll know what I mean.

pointers

I love pointers! They make a lot of things more simple, faster and efficient. A classic example is sorting data. Would you sort an array and copy the data each time or would you sort a linked list and just swap pointers? Ever used callback functions? Just another point(er) ;)
 

Offline AndyC_772

  • Super Contributor
  • ***
  • Posts: 4206
  • Country: gb
  • Professional design engineer
    • Cawte Engineering | Reliable Electronics
Re: while loop in software
« Reply #85 on: December 18, 2014, 12:50:36 pm »
Quite.  It's as daft as suggesting people should avoid using pointers at all costs.
Please don't misunderstand; I'm not trying to make a point here, I genuinely want to learn. An ever-increasing part of my job is embedded firmware development, and I want to get it right - or at least, learn the "rules" so I can break them properly.

I like while{} loops, my code is full of them. What should I be doing instead, and why?

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #86 on: December 18, 2014, 01:07:27 pm »
Surely a perfectly good, generic solution to the "problem" of the loop never terminating, is to write code of the form:

Code: [Select]
while ((condition is true) && (there is still likelihood that condition will become false at some point in the future))
{
  do stuff that affects condition;
  check that it's still reasonable to be looping;
}

Actually, it's not harder to make a for() loop endless by mistake than a while() loop. That seems to be a prejudice. The additional condition would be something for an error tolerant high reliability code, and for() would need that too.
« Last Edit: December 18, 2014, 01:11:44 pm by madires »
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #87 on: December 18, 2014, 01:20:50 pm »
Well, as someone who wasn't force-fed pointers early in his programming career, I don't see the need for the damn things.  I understand their history and how they were used to create and access arrays before arrays became a formal structure, and so on.  I know what they do, what they don't do, and why people use them.
I still don't see the need for the effing things.

If you were designing a language, and someone wants to pass a huge structure or array between functions, how would you acheive this?  Would you copy this enormous data structure onto the heap, massively slowing program execution and greatly increasing memory requirements, or would you pass a reference?  Undoubtedly you would choose the latter in nearly all circumstances.  Passing by reference is using a pointer, even though it may be done "under the hood".

A major part of the power of C is the ability to explicitly use and manipulate pointers, and they are absolutely nothing to be afraid of once you learn to use them correctly.  Suggesting C should be avoided because it uses pointers is like saying cars should be avoided because they use wheels.
Well, hey, there's my point, except glossed over and ignored.

If passing by reference is the same as using a pointer, why use pointers?  Syntactically it is stupid and introduces yet another very common source of bugs and exploits in C programs.

Pointer syntax feels as archaic as using the horse and carriage as a primary means of transport, to me. 

Inherent bounds checking doesn't exist in C.  Is that also a good thing?  Hell no it isn't.  Heartbleed and all the hell it caused is the result of one smart programmer making a mistake that the language should not have allowed him to make.  Once he saw the error, it was fixed in literally a few seconds.

How can ANYONE argue for a language that allows such stupidity?
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #88 on: December 18, 2014, 01:23:07 pm »
Actually, it's not harder to make a for() loop endless by mistake than a while() loop. That seems to be a prejudice. 
I agree in theory you're right IMO but in practice I guess it might be easier to detect an infinite loop when the escape condition and the manner at which this escape condition will be reached is in the same statement as the for( ; ; ) does.

For instance Ex1 vs Ex2 almost no programmer I know will use Ex2 for this example.

Ex1:
for(x=0;x<5;x++)
{
  DoSomething();
}

Ex2:
x=0;
while(x<5)
{
  DoSomething();
  x++;
}

Then there is this ever ongoing discussion if one for an infinite loop should use A) or B), if I am working with a new compiler I always check the assembly if it makes a difference and if so what changes.

A) while(true){}  or while(1) {}
B) for( ; ; )
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #89 on: December 18, 2014, 01:52:13 pm »
Inherent bounds checking doesn't exist in C.  Is that also a good thing?  Hell no it isn't.  Heartbleed and all the hell it caused is the result of one smart programmer making a mistake that the language should not have allowed him to make.  Once he saw the error, it was fixed in literally a few seconds.

How can ANYONE argue for a language that allows such stupidity?

Following your argumentation we should drop assembler too  >:D Either you take care about those issues yourself or you choose some language doing that for you. But the compiler of a programming language doing all the sanity checking can fail too. And all programs compiled with that compiler will have the same security issue. We've seen too much examples of that so far. My question would be, why are so many programmers doing the same stupid mistakes all over again? Why don't colleges/universities teach students how to write secure code? Why do many coders think that the right language would fix all problems?
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #90 on: December 18, 2014, 02:35:21 pm »
Following your argumentation we should drop assembler too  >:D Either you take care about those issues yourself or you choose some language doing that for you. But the compiler of a programming language doing all the sanity checking can fail too. And all programs compiled with that compiler will have the same security issue. We've seen too much examples of that so far. My question would be, why are so many programmers doing the same stupid mistakes all over again? Why don't colleges/universities teach students how to write secure code? Why do many coders think that the right language would fix all problems?

If assembly was the only way to write software for the majority of microcontrollers, I would be making the exact same argument.

Assembly isn't the only way to write for micros, so I'm not saying it should be avoided.

I'm saying that being happy with C as the only non-assembly language one can use in most cases is not defensible.  I see the surge of interest in microcontroller programming lately, thanks to the Arduino and this "Internet of things" and I am happy.  I think of all those new C devs making all those same, stupid mistakes in all those devices and I am not happy.

We should be further along than this.  We have languages that don't require the use of pointers, that compile to fast machine code, we just choose not to use them on micros.  Why?

If there is one thing I have noticed about C developers, it is that they truly believe that C is the alpha and the omega in terms of true development.  There is no room for anything else, and other languages are all toys.

I'm saying that other languages have real benefits and that C is a pile of shit and should he avoided.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #91 on: December 18, 2014, 02:42:32 pm »
Would someone mind please explaining what they think should be used instead of a while{} loop, and why the alternative is better?

Quite.  It's as daft as suggesting people should avoid using pointers at all costs.

Sounds like Dartmouth BASIC, and indeed most BASICs until about 1980.
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #92 on: December 18, 2014, 02:43:09 pm »
We should be further along than this.  We have languages that don't require the use of pointers, that compile to fast machine code, we just choose not to use them on micros.  Why?
What we need is a compiler that does not throw 100 irrelevant errors for forgetting a single ; in a header file.
We need a compiler that will have some extra intelligence telling the programmer he missed a ; in that header file.
We need a compiler that handles (misuse) of  pointers, and many compilers already warn about writing outside arrays if the size is known at compile time. But with dynamic sizes the compiler is not able to see what is going on.
So if we don't get smarter compilers , we sure don't need another higher level programming language slurping up an extra few k's of precious memory:
we need (more) intelligent software engineers ;)
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #93 on: December 18, 2014, 02:48:38 pm »
If passing by reference is the same as using a pointer, why use pointers?  Syntactically it is stupid and introduces yet another very common source of bugs and exploits in C programs.

The style around here says to use c++ references for const pass by reference and pointers for mutables. Not sure why but I guess there is some thinking behind it.

Once you get used to a certain style it becomes a second nature and it eliminates stupid dilemmas.
 

Offline AG6QR

  • Frequent Contributor
  • **
  • Posts: 857
  • Country: us
    • AG6QR Blog
Re: while loop in software
« Reply #94 on: December 18, 2014, 05:05:27 pm »
If passing by reference is the same as using a pointer, why use pointers?  Syntactically it is stupid and introduces yet another very common source of bugs and exploits in C programs.

Only one of the uses of pointers is to pass parameters by reference.  A much more rich and essential use of pointers is to build and traverse complex data structures, like linked lists, binary trees, directed graphs, etc.

I'll grant that those types of data structures don't necessarily see a lot of use in typical embedded microcontroller software.  But for software implementing complex algorithms where performance matters, it is essential to be able to build and traverse data structures that use some notion of pointers.

Yes, it is possible to take the FORTRAN approach, where statically declared arrays are the only aggregating data type, and an array index can be used as a pointer, of sorts.  But that is at least as prone to semantic bugs as direct manipulation of pointers is, and it doesn't allow dynamic sizing of the data structures.
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #95 on: December 18, 2014, 05:57:29 pm »
Quite.  It's as daft as suggesting people should avoid using pointers at all costs.
Please don't misunderstand; I'm not trying to make a point here, I genuinely want to learn. An ever-increasing part of my job is embedded firmware development, and I want to get it right - or at least, learn the "rules" so I can break them properly.

I like while{} loops, my code is full of them. What should I be doing instead, and why?

I think you misunderstood my position on this.  I'm saying that trying to avoid while() loops is as daft as trying to avoid pointers.  They are both useful tools when used correctly and there's no reason to avoid either of them.  As with any tools, improper use will inevitably lead to pain...
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #96 on: December 18, 2014, 06:23:17 pm »
Inherent bounds checking doesn't exist in C.  Is that also a good thing?  Hell no it isn't.
why dont you tell the ieee or computing comitte or the people in power that?

Following your argumentation we should drop assembler too
and any OS built from that or from other lower level language, or the silicons and molecules to store the memory at, because they are not safe, they dont have inherent boundary check. :D

why did we even code at all in the first place? we created a solution for the problem, and then the solution created another problem for us, well that is certainly an infinite loop. how do we expect a perfect thing from an imperfect beings? GIGO. Garbage In is the "human"... ;)
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 Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #97 on: December 18, 2014, 09:28:26 pm »
You seem to be telling me that I don't believe that coding is useful.  That isn't my stance.

My stance is that things COULD be better, but we ignore that shit and dont implement better language features because that shit isn't C and if it isn't vanilla decrepit archaic C, then it's a toy language for little babies.

I don't believe that ignoring advances in automation and language syntax clarity is a good stance to take.  We have tools that can find bugs like heartbleed in less time than it takes a human brain to fire a single neuron, yet we don't use those tools because too many C developers have so much hubris that they can't see things as they really are.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #98 on: December 18, 2014, 09:45:30 pm »
Also, I understand that the errors are all input by humans and I'm not saying that we get rid of humans.

I'm saying that things could be better, I'm not advocating for perfection.  I'm not saying "perfection or nothing," I'm saying "if someone is dead set on using C, let's assist the developer through automation, and use the computer for things that computers are very good at, like analyzing thousands of lines of code at a time looking for common mistakes, like the mistake that created heartbleed."

I'm saying let the human do things that humans are good at, and let the computer do things that computers are good at.

I want to knock the hubris out of every C developer that thinks that C is all that is needed, or is all that is useful.

 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2803
  • Country: nz
Re: while loop in software
« Reply #99 on: December 18, 2014, 11:21:09 pm »
I want to knock the hubris out of every C developer that thinks that C is all that is needed, or is all that is useful.

Programming languages is after all a popularity contest. If 60% of people use C (source http://langpop.com/).

If you are a lone wolf howling at the horrors of C, then you have to ask yourself....

* Do some pretty smart people use C?
* Am I smarter than most of them?
* What do I see that others don't?
* What do others see that I don't?
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 Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #100 on: December 19, 2014, 12:40:38 am »
I am not going to say that I am smarter or more talented than anyone. 

Yes, smart people use C. 

Yes, smart people avoid C.

I do know for a fact that we could make a lot of things a lot easier with automation, including software development, yet we either choose not to, or simply believe that we don't need to because we believe we are better than we really are at things.  Hubris.

 

Offline dannyf

  • Super Contributor
  • ***
  • Posts: 8221
  • Country: 00
Re: while loop in software
« Reply #101 on: December 19, 2014, 12:46:41 am »
Quote
Programming languages is after all a popularity contest.

I am not so sure.

Quote
If you are a lone wolf howling at the horrors of C, then you have to ask yourself..

Why? You pick a tool for your application. It is possible that sometimes existing code base plays a role in one's decision on languages but I have to say that in my experience, that's fairly low on my priority list.
================================
https://dannyelectronics.wordpress.com/
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #102 on: December 19, 2014, 03:13:53 am »
I highly recommend this MOOC about algorithms: https://www.coursera.org/course/algs4partI
(and it's follow-on "partII", as well.)

For one thing, its wonderfully taught, with great lectures, a good set of online resources, meaningful assignments, and so on.  Just from "execution" point of view, it's one of the best MOOCs I've seen.

Secondly, you'll learn about a bunch of neat algorithms, complete with some of their applications.  If you're like me and have worked in the embedded world trying to low-level code just to get the right data into and out of a chip, you probably haven't needed to implement any fancy algorithms (arguably, hardly anyone ever needs to implement fancy algorithms; if a problem space is important enough to cause fancy algorithms, then you can go out and import the relevant code from somewhere.)  Maybe something wasn't even invented (or popular) when you last took a CS class.

Thirdly, it's a fascinating meta-glimpse into how "computer science" is different from "software engineering" or "programming."  You'll gain an understanding of why there is so much enthusiasm (in certain circles) for new languages like Java.  And concepts like recursion.  The class is taught using Java, but at a very basic level where you're truly using some of the important concepts implemented by Java, rather than some package of classes that someone says are useful for a particular purpose.  If you're familiar with some other language, you shouldn't have any trouble converting the Java examples.  (The class/book has previously used other languages, so the instructor has things really distilled down to core concepts.  Also, there's a fair amount of discussion of Java internals (particularly WRT size of data objects) and limitations that I found really useful.)
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2803
  • Country: nz
Re: while loop in software
« Reply #103 on: December 19, 2014, 03:54:15 am »
Quote
Programming languages is after all a popularity contest.

I am not so sure.

Why are you not so sure? I've seen too many things fall in and out of fashion to say that one tool is superior to the others - things like Java, Javascript, Perl, PHP, Python, COBOL, BASIC, Pascal, Go, Delphi, Smalltalk, Fortran, LISP, PL/1, C++, Visual Basic, C#,  PL/SQL, SQL Forms, AWK/sed and so on, endless GUI programming environments, endless different IDEs, different design methodologies JSP, three-tiered applications, data driven development, design patterns, functional programming languages, Agile, blah, blah, blah,,

Some of the languages bring new things to the table, and others take them away. None of them solve the core problem that programming is hard, and any programming language that is expressive enough to be useful makes it easy to write buggy code.

Just look through any programmers bookshelf who is older than 40 - the only books of value are anything on algorithms and the K+R ANSI C book. For all the others, at the time they were purchased they were considered important to spend real money, now they are junk.

In general it isn't the tools you use that determine results, it is the people who use them. It is a fact of life that 50% of projects will get sub-average results, and a great team with only shoddy tool-sets will outshine a shoddy team with the best tools.

So if I need something done, and it is appropriate, give me a good C programmer and let him use it's unbounded arrays, pointers, and while() loops. Heck, they can even use "goto"s for trapping errors if they must.

Just don't give me an sub-average programmer and demand that they use a tool-set that is a language designer's wet dream, believing it will give spectacular results. It wont.
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #104 on: December 19, 2014, 06:24:28 am »
Fascinating how a general question about the use cases of while loops evolves into a philosophical debate on programming languages.

Are we off-topic already?
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #105 on: December 19, 2014, 06:51:42 am »
I guess the question is, can you create a program that totally avoids while loops and is still readable and maintainable?
Taking in consideration that an unconditional goto looping back is the same thing as a while (1) or for(;;) statement.

Unless you are talking about functional languages, but they still have while loops to read their messages process them and spit them out, even if there is no concurrency it all loops.

Event driven databases? maybe they don't need loops but something is monitoring the interrupts or whatever triggers the events and that's probably looping.

Why would the terms of "main loop" or "event loop" would be used if it doesn't imply you need such loop?

But yeah, you can write programs that are a one off, but if you want to call that program again, something is looping.

I think that most (over 99.9%) of the programs loop, for/while/goto same difference.
« Last Edit: December 19, 2014, 07:39:12 am by miguelvp »
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #106 on: December 19, 2014, 07:37:01 am »
My stance is that things COULD be better, but we ignore that shit and dont implement better language features because that shit isn't C
it isnt particularly about C or else. talking about say... inherent/built in boundary check in a language is a root thing when trying to inventing one particularly new language. and then further it will related to or mess with hardware/cpu core design. software boundary check is expensive (in real software), even with hardware i guess, we are talking PC level intel real gigas i-core cpu and ram here, let alone embedded world. so its decided not to have boundary check, they left it to human the programmer to handle it, who decided that? those sharp people up there whose job designing a language or laying out specifications, and the majority in the clan below ofcourse.. i guess. another way to put it, is the freedom to do or not to do. once the boundary check is stuck in a language, nothing you can do about it, even a simple homebrew memset or memzero will take so long. like an automatic car without manual overide knob try running jungle track or curvy/difficult road uphill i hate that. for the minority of the clan who think no boundary check is an abomination, they have the right to use more modern language such as "managed" type of language, go for C# or VB#, it has wonderful automation, thats the improvement made for the problem, thats modern. i dont say we should not improve, i only saying, is the direction of your improvement right? if people think a new language should be invented, then go for it but dont impose other people from exercising their freedom in software development. heck i believe even the modern "managed" language are built on top of "unmanaged" language such as c/c++. think why? the people who decided that are not muggles.
« Last Edit: December 19, 2014, 07:42:09 am by Mechatrommer »
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 mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #107 on: December 19, 2014, 09:52:10 pm »
I want to knock the hubris out of every C developer that thinks that C is all that is needed, or is all that is useful.

Why have you set out on this strange and lonely mission?  Quite honestly it sounds like you've burnt your fingers trying to develop something in C and have somehow decided it was the fault of the language.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #108 on: December 19, 2014, 10:08:53 pm »
I agree with Rigby and there are alternatives like PL/M and ADA which take care of a lot of potential problems with pointers. A modern choice would be Lua. With larger amounts of RAM and flash the amount of software which deals with hardware is only a fraction of the entire firmware. It makes perfect sense to use a higher level language for the logic & data processing part of the firmware if that programming language helps to avoid the many pitfalls C offers.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #109 on: December 19, 2014, 10:30:40 pm »
Why have you set out on this strange and lonely mission?  Quite honestly it sounds like you've burnt your fingers trying to develop something in C and have somehow decided it was the fault of the language.

Buffer overflows are the fault of the language ... unbounded pointers should be the exception, not the rule. If we had started using run time bound checking (and languages which make it awkward to use unbounded pointers) when we started to realize how easy bugs and exploits were created by not doing so then performance wouldn't even have been an issue at this point, ISA would have included fast instructions for it.

The continued use of C in internet facing systems is negligent (SQL too for that matter).
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #110 on: December 19, 2014, 10:43:50 pm »
I want to knock the hubris out of every C developer that thinks that C is all that is needed, or is all that is useful.

Why have you set out on this strange and lonely mission?  Quite honestly it sounds like you've burnt your fingers trying to develop something in C and have somehow decided it was the fault of the language.

I've developed in C plenty.  I have lots of code in production in various places and on various platforms, from microcontrollers to PC applications.

My distaste of C derives purely from use of and experience with C and in comparing C to other languages.

I see what computers can do, and I see how C is very much unchanged in so many ways after over 40 years.  Computers are supposed to aid us.  With C, the computer just gets in the way, lets you lay little traps that no one will notice for years, and almost aids developers in making mistakes.  My primary complaint about that is that NO ONE SEEMS TO CARE.  Virtually every C developer I've known, when I mention how easy common mistakes are, they respond with something like "yeah, so don't do that."  You're sitting at a computer which was partially DESIGNED to detect errors that humans are prone to make and we still rarely use them to detect errors that humans are prone to make, purely because we each have so much misplaced confidence in our own abilities. 

The result is that every new C developer makes these mistakes again and again, and we constantly hear about code that is vulnerable to buffer overflow or memcopy exploits or whatever the bug du jour is lately.

We could use the computer to aid us as C developers, yet we choose not to.  This is my complaint.  We are so full of ourselves to think if we just remember not to do a bad thing that no bad things will happen in our code.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #111 on: December 19, 2014, 10:49:54 pm »
Some languages are more "high-level" than others - they abstract the hardware more. C does fewer things by itself, making its code closer to what the machine is directly capable of. Why do we have to bicker about whether we'd rather it do more or less for us? That doesn't make it a poor language, that just makes it closer to the "metal" - and sure, if you don't need to work that close to the metal, don't. That doesn't mean there's something wrong with tools that are intended for that sort of work.

Instead of bitching about how the hammer that is C is just terrible at driving screws, why not restrict it to nail-driving and use something else for the screws?
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #112 on: December 20, 2014, 12:05:43 am »
Because C is not a good hammer or a good screwdriver.  C is a kit that aids one in the creation of stupid mistakes and security vulnerabilities, and everyone is OK with that.

Ya know what?  Clearly I'm wrong.  Clearly a language that aids the developer in the production of shit code is the right thing.  Ok.  I'll just drop out of this conversation and let you all have your C circle jerk.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #113 on: December 20, 2014, 12:10:18 am »
C is a kit that aids one in the creation of stupid mistakes and security vulnerabilities when used for the wrong tasks - fixed that for you.

I'll just drop out of this conversation and let you all have your C circle jerk.

Ooh, a C circle jerk - sounds like fun! Where?
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #114 on: December 20, 2014, 12:29:55 am »
Performance is one point, but what was somewhat ignored here is that languages with pointers are actually needed to implement low level stuff like writing to peripheral registers. And sometimes even C is not low level enough and you'll need inline assembly just to write to a special function register or to use a specific opcode (like count leading zeroes and stuff like this).
Still, even this is only possible if the compilers allows passing of register/automatic variables between "high level" (i.e. C) and assembly language.

Also, when talking about implementing an operating system, priority manipulation, context switching and so, you'll need at least a language like C that allows low level access.

IMHO, there will alway be a place for C and assembly for low level and time critical stuff.
Personally, I do all my PC stuff in Java (if I want it platform independent) or C# (if I need some Windows specific libraries), but all microcontroller stuff in C.
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 #115 on: December 20, 2014, 01:23:35 am »
when people kill someone with a hammer... blame the hammer :D

My primary complaint about that is that NO ONE SEEMS TO CARE.
i guess its not that they not or havent care, but if they do care, it will create another problem for them and the humanity. as i said, let your voice reach up there in the ieee comitte. if they decide that your decision is wiser, i believe they'll listen.
« Last Edit: December 20, 2014, 01:32:06 am by Mechatrommer »
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 f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #116 on: December 20, 2014, 01:41:01 am »
It's really funny to read that some people hate C because it's too low level, and developer have to take care of everything with it.

Errrr, isn't the job of the developer to do that?! Isn't the intrinsic part of the job?. Yeah, you have to take care where you move your pointers, your memory allocations, and stuff like that, wow, what a deal.

C is quite low level, permissive, but it's damn powerful and light, and it's the way it has been designed.

It's fourty years old, yeah, and still used and loved, ask yourself why (I won't bet anything on these <whatever letter># crap, or new fashion language, will survive 20).

C, C++ and ASM will survive us, all of us.

---
Daniel
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #117 on: December 20, 2014, 01:48:00 am »
I don't hate C.  I hate that C devs flatly reject advances in software development. 

I also hate behavior just like what you just typed up.  Dismissal of my point of solely because it does not match your own.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #118 on: December 20, 2014, 01:50:23 am »
I don't hate C.

Because C is not a good hammer or a good screwdriver.  C is a kit that aids one in the creation of stupid mistakes and security vulnerabilities, and everyone is OK with that.

... a language that aids the developer in the production of shit code ...

My distaste of C derives purely from use of and experience with C and in comparing C to other languages.
...
With C, the computer just gets in the way, lets you lay little traps that no one will notice for years, and almost aids developers in making mistakes.

Presented without comment.
« Last Edit: December 20, 2014, 01:54:10 am by c4757p »
No longer active here - try the IRC channel if you just can't be without me :)
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #119 on: December 20, 2014, 01:58:56 am »
go for visual basic 6 my friend... it has array bound check in every compile option, your problem solved! its been 14 years old and i'm still using it, with 99.99999% array bound check turned OFF ;)
a boundary check in each 2 billions iteration of memory access in my dumb and stupid example earlier is a epic!
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 suicidaleggroll

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
Re: while loop in software
« Reply #120 on: December 20, 2014, 02:01:02 am »
There are arguments for both paradigms.

Most high level languages have all kinds of error checking built in.  They're big, they require gobs of resources, and they're slow (I'm looking at you IDL, Matlab, Python, etc.).  They're like a programmer's sandbox.  You can have fun, you can play around, but you have to stay inside the walls or the school teacher scolds you.  You're allowed to do what the language allows you to do, no more.  This makes the language safe.  Any out of bounds array references will throw an error, any loop errors will throw an error.  Any dangerous errors of any kind will throw an error.  They're great for prototyping when you don't want to bring down the machine, but as I said before, they're big, they require gobs of resources, they're slow, and you're only allowed to do what the language allows you to do.

Low level languages like C or Assembly take the other approach.  They assume you know what you're doing and get the hell out of the way.  This makes them fast...very fast, and it also makes them insanely flexible and powerful, BUT it makes them vulnerable.  If you screw up, you can do all sorts of damage.

High level languages are great when resources aren't a problem, execution speed is not a problem, and you're only doing "sandbox" activities.  When you get outside of that goldilocks regime, you need to move to a low level language that gets out of the way and lets you do what you need to do.  Of course when you're in this realm, any mistakes are on you, the language won't hold your hand and babysit you through the debugging process.  That's not a fault of the language, it's an inherent byproduct of the types of tools you need to use when working in this domain.

That doesn't mean C is crap and needs to die, it just means that you should only use C when it's the right tool for the job, which it often is...
 

Offline suicidaleggroll

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
Re: while loop in software
« Reply #121 on: December 20, 2014, 02:02:24 am »
go for visual basic 6 my friend... it has array bound check in every compile option, your problem solved!
Every C compiler has a bounds check flag you can enable if you want.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #122 on: December 20, 2014, 02:05:11 am »
I like C a lot.  It was one of the first languages to reject the idea that a large runtime library should be part of the language definition, leading relatively directly to a degree of portability across Architectures and Environments that has seldom been equaled (and I think that that is largely responsible for its success.) (and at a time when other languages (Looking at PL/1 and Ada) were including HUGE runtimes that were incompatible with the language definition.  (It always particularly annoyed me that the Pascal built-in functions did things that were not permitted of user functions (variable number of arguments in Print(), for example.))

I do wish that they had included strings as part of the language, though.  There's nothing wrong with pointers in general, but having to use them ALL THE TIME to deal with something as common as strings is both annoying and error-prone.
 

Offline Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #123 on: December 20, 2014, 02:05:50 am »
More likely than not C is why Sony Pictures is being destroyed. More likely than not C is why a German steel mill has a load of scrap on it's hands where they once had expensive machinery. C is a weapon of mass destruction.
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #124 on: December 20, 2014, 02:08:57 am »
go for visual basic 6 my friend... it has array bound check in every compile option, your problem solved!
Every C compiler has a bounds check flag you can enable if you want.

BTW, is VB even a language? :-D
It's not even portable :palm:

---
Daniel
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #125 on: December 20, 2014, 02:17:41 am »
More likely than not C is why Sony Pictures is being destroyed. More likely than not C is why a German steel mill has a load of scrap on it's hands where they once had expensive machinery. C is a weapon of mass destruction.

The idea that these issues would go away if people stopped using C is cute.

BTW, is VB even a language? :-D
It's not even portable :palm:

Nor potable, which is what I first read.

Seriously, I don't recommend it.
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #126 on: December 20, 2014, 02:22:13 am »
The idea that these issues would go away if people stopped using C is cute.

Criminals are not immune to the cost-benefit principle.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #127 on: December 20, 2014, 02:43:28 am »
I don't hate C.  I hate that C devs flatly reject advances in software development. 

I also hate behavior just like what you just typed up.  Dismissal of my point of solely because it does not match your own.

Rigby, what language would you recommend for programming small MCU's instead of C/C++?
 

Offline vvanders

  • Regular Contributor
  • *
  • Posts: 124
Re: while loop in software
« Reply #128 on: December 20, 2014, 03:19:48 am »
More likely than not C is why Sony Pictures is being destroyed. More likely than not C is why a German steel mill has a load of scrap on it's hands where they once had expensive machinery. C is a weapon of mass destruction.
That's the biggest crock I've heard. If you took 2 seconds to look into the issue you'd see that it's the result of spear phishing: http://arstechnica.com/security/2014/12/computer-intrusion-inflicts-massive-damage-on-german-steel-factory/

There are many high level languages that do what you want. If you want bounds checking use them. There's a reason for C's success and if programming was easy then none of us would have jobs.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #129 on: December 20, 2014, 03:58:45 am »

Rigby, what language would you recommend for programming small MCU's instead of C/C++?

Not a lot of choice, is there.  Since all of you are so blindly in love with C to even admit it has issues, I don't see that ever changing. 

 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #130 on: December 20, 2014, 04:00:47 am »
Oh I see, this is one of those hypothetical, Wouldn't It Be Nice If arguments.

I want a unicorn.
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #131 on: December 20, 2014, 04:05:36 am »
The idea that these issues would go away if people stopped using C is cute.

Who said that these issues would go away?  I didn't.  Would disuse of C for certain things mitigate these issues a bit?  You and I both know that it would.

That's all I'm trying to say -- C is NOT the ultimate language in its current form, and I'm getting a hell of a lot of resistance on that.  I don't understand why.  I'm saying "hey, things could be better if a few of us wanted that" and it feels like I'm getting back something like "fuck Rigby, am I right, haha what a loser!  Try VB, LOSER! LOL" 
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #132 on: December 20, 2014, 04:11:58 am »
Oh I see, this is one of those hypothetical, Wouldn't It Be Nice If arguments.

I want a unicorn.
I never said that there were alternatives today... I said that languages have advanced and C has not.  I said things could be better.

Now, you're telling me that because no alternative exists right this moment that my wish for a better fucking development paradigm for micros is like wishing for a unicorn?

What the FUCK are you people smoking?
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #133 on: December 20, 2014, 04:37:24 am »
I have no problem with what you claim to be saying, it's what you are saying in between those claims that's absurd...
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #134 on: December 20, 2014, 04:54:18 am »
Here's a potential replacement for C on micros.

http://dlang.org/comparison.html

I don't know much about this language, yet, but it is open source, uses C-like syntax, doesn't use pointers except when they are NEEDED, allows direct access to hardware, and compiles to machine code, just like C.

So here we have something that shows promise, and could prevent a lot of errors that are prone to happen with C. 

Now, quick; tell me what a jackass I am and how wrong I am.  Rise up and strike me down, and your transformation into a high school cheerleader clique will be complete.
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2803
  • Country: nz
Re: while loop in software
« Reply #135 on: December 20, 2014, 06:31:08 am »
Sounds a lot like Turbo Pascal, 31 years ago.

Only sort of kidding.

That is how it was marketed. Strong typing. No pointers except where needed. Strings with lengths at the start, bounds checking on arrays better modularity, all the speed of C, a better language for system-level work.

It was also much admired by teachers for doing things 'the right way' and used in tertiary courses (like Java was 10 years ago... what do they use now???).

I sort of liked ir.
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 zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #136 on: December 20, 2014, 07:40:29 am »

Rigby, what language would you recommend for programming small MCU's instead of C/C++?

Not a lot of choice, is there.  Since all of you are so blindly in love with C to even admit it has issues, I don't see that ever changing.

There are non C/C++ languages that are popular when programming real computers so possibly the issue is not that people don't accept better languages but that low level language such as C/C++ are the best fit for microcontrollers.

Electric Imp for example support a higher level language (at least when it comes to memory management) most likely so they can sandbox user's programs but I would guess that they use C/C++ for their own stuff.  https://electricimp.com/docs/squirrel/squirrelcrib/
 

 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #137 on: December 20, 2014, 08:37:47 am »
Sounds a lot like Turbo Pascal, 31 years ago.

Only sort of kidding.

That is how it was marketed. Strong typing. No pointers except where needed. Strings with lengths at the start, bounds checking on arrays better modularity, all the speed of C, a better language for system-level work.

It was also much admired by teachers for doing things 'the right way' and used in tertiary courses (like Java was 10 years ago... what do they use now???).

I sort of liked ir.

I wrote an awful lot of Turbo Pascal back in the day, not just on the PC but they had a Mac version too in the end. Knocked spots off the competitors for performance, remember this was a time when many PCs didn't even have a hard drive, everything was stored on floppies. Borland stored everything, the IDE, the source code and the compiled program in RAM to massively improve development time. Microsoft had a Pascal compiler that was dog slow because ot relied on disk for everything. Later on, when doing C, I used to develop everything in the super fast Borland Turbo C IDE and then, when ready, recompile later in the uber slow Microsoft C, the choice of my employer.

Anyone remember that dog slow, almost unuseable, Programmer's Workbench (PWB) that Microsoft brought out in answer to Borland's IDE? Microsoft just didn't get it.
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #138 on: December 20, 2014, 09:15:35 am »
I've written code in assembler, Basic, Pascal, Modula, Comal, C, C++, unix shell scripts, awk scripts, DOS batch scripts, Java, perl, PHP and some stuff more, but I'm still happy with C. And because I know C's weaknesses, I know how to deal with them. Sometimes those weaknesses are quite useful to solve a problem in a simple way. The same applies to other languages as well. But you'll find out that a secure and idiot-proof language makes programming cumbersome and programs slow.
« Last Edit: December 20, 2014, 12:53:32 pm by madires »
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #139 on: December 20, 2014, 10:15:03 am »
Here's a potential replacement for C on micros.
http://dlang.org/comparison.html
...
Yeah, but will anybody care to write a D compiler for ARM, for Atmel, for Freescale's  PowerPC (Esys) cores or even more obscure stuff (Infinion Tricore or Freescale eTPU)?
Writing/adapting a compiler for a specific core architecture is not an easy task. Optimization strategies differ, pipeline effects have to be considered and so on. Even between cores of the same family, the command set differs. There are even cores with two switchable instruction sets, dedicated SIMD or floating point engines with very specific implementations etc.
The only reason that we can develop for ARM and Atmel with freely available compilers is that C was and is of such importance that GCC was started as open source project.
Anyway, in industrial applications with safety to consider, you usually want to use a compiler which has certain certifications and guarantees to work around known errata of the supported cores.
This means though that some software vendor like BlueRiver and the likes is interested to develop that compiler for you - which they only do if there is enough demand for it.
And honestly, for the next ten years to come, the Demand for C/C++ will be much higher than for somewhat exotic languages like D or Rust or whatever.

So on a microcontroller it's not like on the PC where you can decide freely which language to choose for a project. In the end you kinda need to use C since there is simply no other (stable, robust, certified, performant) other compiler available. The only chance would be to use a higher level language or symbolic tool that creates C code which then needs to be compiled by the default C compiler. Problem is that this increases build time and makes it very hard to debug. Also chance of tool/compiler errors increases.
Trying is the first step towards failure - Homer J. Simpson
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3231
  • Country: gb
Re: while loop in software
« Reply #140 on: December 20, 2014, 10:21:58 am »
I see what computers can do, and I see how C is very much unchanged in so many ways after over 40 years.

Fashions come and go, but style is forever.

Computers are supposed to aid us.  With C, the computer just gets in the way, lets you lay little traps that no one will notice for years, and almost aids developers in making mistakes.  My primary complaint about that is that NO ONE SEEMS TO CARE.  Virtually every C developer I've known, when I mention how easy common mistakes are, they respond with something like "yeah, so don't do that."  You're sitting at a computer which was partially DESIGNED to detect errors that humans are prone to make and we still rarely use them to detect errors that humans are prone to make, purely because we each have so much misplaced confidence in our own abilities. 

The result is that every new C developer makes these mistakes again and again, and we constantly hear about code that is vulnerable to buffer overflow or memcopy exploits or whatever the bug du jour is lately.

We could use the computer to aid us as C developers, yet we choose not to.  This is my complaint.  We are so full of ourselves to think if we just remember not to do a bad thing that no bad things will happen in our code.

So you are suggesting someone invents a utopian language that won't permit the programmer to make any mistakes, and yet gives the runtime performance as C? Sounds great, why don't you do it?  You'd certainly make a lot of money.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #141 on: December 20, 2014, 11:01:41 am »
No embedded Lua? At least Lua seems way more mainstream than D.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #142 on: December 20, 2014, 12:26:45 pm »
go for visual basic 6 my friend... it has array bound check in every compile option, your problem solved!
Every C compiler has a bounds check flag you can enable if you want.
BTW, is VB even a language? :-D
It's not even portable :palm:
---
Daniel
VB hateboy (linux/mac/c fanboy) joining the club, welcome!... yes VB is a language, you seem to miss what a "language" means. and i'm guessing you are the new guy or never code in VB, never link it to external C/asm (read as super fast and efficient) code/dll, and never get the idea that there is/are few VB IDE for micros, never appreciate how hard the hundreds lines of code just for windows creation and events handling etc... granted there is no VB for linux or mac because VB was invented by the "BIG" guy from M$$$$. mac & linux are small, if it aint for W$$$ i'm not buying :P :P :P you taste what? lemon? :P

edit: and i dont need to be portable because i can live without linux and mac. and portabilitty is not something you embed or as a criterion in a language, it can be important for the success of a particular language, but not that important to decide whether one is a language or not. portability is about people providing platform or IDE / compiler for the particular machine. if the big guy decided VB to be portable, they will build the IDE for other OS, but they opt to not to. if no one is building java distribution for windows, java app will not even be portable to windows, you feel that?
« Last Edit: December 20, 2014, 12:35:21 pm by Mechatrommer »
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 Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #143 on: December 20, 2014, 12:44:09 pm »
C is for advanced programmers. Go play with Java or Microsoft Java (C#) if you want rubber matting all around.
Instead of being lazy and fixing the result of your mistakes, go and fix your mistakes, please.

(already 10 pages of  :rant: on while loops, intriguing)
 

Offline dannyf

  • Super Contributor
  • ***
  • Posts: 8221
  • Country: 00
Re: while loop in software
« Reply #144 on: December 20, 2014, 12:47:52 pm »
Quote
C is for advanced programmers.

Depending on what you meant by "advanced". I consider those working on Android / IOS everybit as advanced, if not more.

Quote
(already 10 pages of  :rant: on while loops, intriguing)

Yes, and more importantly, amazing.

That's the (most?) interesting thing about dealing with engineers - everything is black and white and answers must be right or wrong.

So simpleton.
================================
https://dannyelectronics.wordpress.com/
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #145 on: December 20, 2014, 01:02:53 pm »
Quote
(already 10 pages of  :rant: on while loops, intriguing)
Yes, and more importantly, amazing.
let me hint you the list...
1) religion
2) computing theology... trolls to linux vs windows / c vs others flamewar (this thread)
3) free energy
4) dso hacking thread
5) audiophoolery
sort of...
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 Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #146 on: December 20, 2014, 01:48:02 pm »
That's the biggest crock I've heard. If you took 2 seconds to look into the issue you'd see that it's the result of spear phishing: http://arstechnica.com/security/2014/12/computer-intrusion-inflicts-massive-damage-on-german-steel-factory/

Phishing gets them on a system, but they will generally want to elevate their privileges ... you don't really want to target the sysadmins directly. Local exploits almost certainly played their part.
 

Offline paulie

  • Frequent Contributor
  • **
  • !
  • Posts: 849
  • Country: us
Re: while loop in software
« Reply #147 on: December 20, 2014, 01:50:14 pm »
thing about dealing with engineers - everything is black and white and answers must be right or wrong.

You seem absolutely convinced this is true. Did it ever occur there is a less extreme viewpoint. That there may be a middle ground and it's not as clear cut as that?
« Last Edit: December 20, 2014, 02:21:46 pm by paulie »
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #148 on: December 20, 2014, 02:04:35 pm »
C is for advanced programmers.
That is a load of crap. That is just like saying 'using a drill press without wearing safety glasses is what real men do'.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #149 on: December 20, 2014, 02:28:40 pm »
So we agree, that while() loops in C are a religious matter? >:D
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #150 on: December 20, 2014, 03:42:08 pm »
So we agree, that while() loops in C are a religious matter? >:D

To answer this question we first need to determine if C itself is good. :)
 

Offline madires

  • Super Contributor
  • ***
  • Posts: 7673
  • Country: de
  • A qualified hobbyist ;)
Re: while loop in software
« Reply #151 on: December 20, 2014, 04:03:17 pm »
So we agree, that while() loops in C are a religious matter? >:D

To answer this question we first need to determine if C itself is good. :)

Intentional spelling error?  ;D

Sorry, couldn't resist.
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #152 on: December 20, 2014, 08:43:32 pm »
go for visual basic 6 my friend... it has array bound check in every compile option, your problem solved!
Every C compiler has a bounds check flag you can enable if you want.
BTW, is VB even a language? :-D
It's not even portable [emoji14]alm:
---
Daniel
VB hateboy (linux/mac/c fanboy) joining the club, welcome!... yes VB is a language, you seem to miss what a "language" means. and i'm guessing you are the new guy or never code in VB, never link it to external C/asm (read as super fast and efficient) code/dll, and never get the idea that there is/are few VB IDE for micros, never appreciate how hard the hundreds lines of code just for windows creation and events handling etc... granted there is no VB for linux or mac because VB was invented by the "BIG" guy from M$$$$. mac & linux are small, if it aint for W$$$ i'm not buying [emoji14] [emoji14] [emoji14] you taste what? lemon? [emoji14]

edit: and i dont need to be portable because i can live without linux and mac. and portabilitty is not something you embed or as a criterion in a language, it can be important for the success of a particular language, but not that important to decide whether one is a language or not. portability is about people providing platform or IDE / compiler for the particular machine. if the big guy decided VB to be portable, they will build the IDE for other OS, but they opt to not to. if no one is building java distribution for windows, java app will not even be portable to windows, you feel that?
Thanks, but here you're wrong. Back in the day, I even used VB (you known,  installing that from zillion of 3"5 floppy), few years ago I had to use it again for some obscure quick and crap proof of concept (yeah,  rewrote the whole this in C++ right after that). So yes, VB is much more a toy ("variant" data(no)type, what a shame) than anything else, these various incompatible runtime you have to install are just PITA. yeah, it's fast and easy to build a window with menu and buttons, but that's it. You want something fast with small memory footprint, try something else, like a real programming language (GFA basic? :-D)

Portability, yeah, that's the key, you know, there are other worlds out of Windows, open you mind.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #153 on: December 21, 2014, 12:16:04 am »
Back in the day, I even used VB (you known,  installing that from zillion of 3"5 floppy) ... You want something fast with small memory footprint, try something else, like a real programming language (GFA basic? :-D)
GFA Basics? seriously?


man dont drag me to your floppy era, i'm done with it. VB today is not the same as VB 20yrs ago. even VB6 is now comparatively alot smaller footprint than say.... java w it distribution (aka runtime environment), NET4 et al the new modernization of computing theology, i cant understand why people are so care about exe footprint anymore in terrabytes era. and my quote on you dont understand what is a "language" because VB is based on "Basic Language", Basic is the language, "Visual" is just the whistle of it. you just like saying "Borland C++" is not a language because it has "Borland" in it. VB and GFA Basics are based on the same language... "Basic". dont recommend VB? dont recommend GFA ;)

few years ago I had to use it again for some obscure quick and crap proof of concept
if hate it, why use it? why dont just build "the proof of concept" right from the start in C? then you dont have to rewrite? or either.. since you build "crap proof of concept", your concept is actually crap? ;)

just for the record, to compare between floppy and "not so modern" era, vb6 somewhere in 2000... i was talking building app for windows, not DOS.

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 Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #154 on: December 21, 2014, 12:26:10 am »
So we agree, that while() loops in C are a religious matter? >:D
To answer this question we first need to determine if C itself is good. :)
Intentional spelling error?  ;D
:-DD
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 zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #155 on: December 21, 2014, 12:30:05 am »
So we agree, that while() loops in C are a religious matter? >:D

To answer this question we first need to determine if C itself is good. :)

Intentional spelling error?  ;D

Sorry, couldn't resist.

Yes, I meant dog.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #156 on: December 21, 2014, 03:38:09 am »
Quote
already 10 pages of  :rant: on while loops,
Well, in fact, No.   Distracted by Trolls, I think.
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #157 on: December 21, 2014, 07:41:02 am »
Back in the day, I even used VB (you known,  installing that from zillion of 3"5 floppy) ... You want something fast with small memory footprint, try something else, like a real programming language (GFA basic? :-D)
GFA Basics? seriously?


man dont drag me to your floppy era, i'm done with it. VB today is not the same as VB 20yrs ago. even VB6 is now comparatively alot smaller footprint than say.... java w it distribution (aka runtime environment), NET4 et al the new modernization of computing theology, i cant understand why people are so care about exe footprint anymore in terrabytes era. and my quote on you dont understand what is a "language" because VB is based on "Basic Language", Basic is the language, "Visual" is just the whistle of it. you just like saying "Borland C++" is not a language because it has "Borland" in it. VB and GFA Basics are based on the same language... "Basic". dont recommend VB? dont recommend GFA ;)

few years ago I had to use it again for some obscure quick and crap proof of concept
if hate it, why use it? why dont just build "the proof of concept" right from the start in C? then you dont have to rewrite? or either.. since you build "crap proof of concept", your concept is actually crap? ;)

just for the record, to compare between floppy and "not so modern" era, vb6 somewhere in 2000... i was talking building app for windows, not DOS.



VB is "based" on basic, but far from it.

GFA was a joke, but it seems you didn't get it :-D. But it was a great think, delivered with its compiler, BTW.

Floppy era ?! Hey, it's history, you can't ignore that :-)

Can you still compile your 20 years old code ? I really doubt it, due to the fact they broke ascendant compatibility numerous times.
Take and old piece of C or C++, you'll be able to compile it without any effort. Could you with your VB code ?

I meant "memory" footprint, not "exe", that's really different. Do you think every computer are i7 based with 16Gb of memory ?! Do you think all computer are running Windows 7 ?...
When I write code, I try to make it a way that it could run a small end computers, I take care about memory footprint, speed, and so on. The points that VB "developers" ignore, or aren't aware of.

.NET is a sin (how many versions windows users have to install ?!), and just try to convince you that it a panacea.

Why not C on the first step, because the hardware that I had to control was delivered with various way to control it. And I had to check if it match our needs, very quickly, no need or time to make a clean software.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #158 on: December 21, 2014, 08:15:59 am »
BASIC was never standardized enough to be able to label any one thing as "only BASIC-like."

Quote
Take and old piece of C or C++, you'll be able to compile it without any effort.
That's pretty laughable.  Pre-posix (first published in 88, and took some time to get widely adopted) C applications had to be customized pretty heavily depending on actual target.  Your chances of compiling a 1990 Windows 3.1 C program of any complexity (even one for CLI) on a modern system "without any effort" are about zero.  (Shucks, going from gcc 2.95 to gcc 3.4, or gcc 3.4 to 4.8, for the same bare-metal cross-target, is likely to require "some" effort.)  (No, wait!  Even with modern package managers and such, trying to compile a good-sized C application from linux, on a Mac, can lead to what I usually call "dependency hell.")
 

Offline 22swg

  • Frequent Contributor
  • **
  • Posts: 274
  • Country: gb
Re: while loop in software
« Reply #159 on: December 21, 2014, 09:48:36 am »
While(on Basic) could I give PureBasic a mention ... http://www.purebasic.com/  very coder friendly..
Check your tongue, your belly and your lust. Better to enjoy someone else’s madness.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #160 on: December 21, 2014, 10:12:46 am »
While(on Basic) could I give PureBasic a mention ... http://www.purebasic.com/  very coder friendly..

Very interesting, does it have while loop?  Is it safe to use it?
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #161 on: December 21, 2014, 12:48:13 pm »
BASIC was never standardized enough to be able to label any one thing as "only BASIC-like."

Quote
Take and old piece of C or C++, you'll be able to compile it without any effort.
That's pretty laughable.  Pre-posix (first published in 88, and took some time to get widely adopted) C applications had to be customized pretty heavily depending on actual target.  Your chances of compiling a 1990 Windows 3.1 C program of any complexity (even one for CLI) on a modern system "without any effort" are about zero.  (Shucks, going from gcc 2.95 to gcc 3.4, or gcc 3.4 to 4.8, for the same bare-metal cross-target, is likely to require "some" effort.)  (No, wait!  Even with modern package managers and such, trying to compile a good-sized C application from linux, on a Mac, can lead to what I usually call "dependency hell.")

I think you missed the word "portability", you're talking about windows 3.1, with its nice undocumented API...

Stick to pure C/C++ (libc and friends), write some abstraction layer, and you'll have to only (re)write the platform specific sections.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #162 on: December 21, 2014, 01:07:39 pm »
That is not going to work. Back in the old days every C compiler had it's own slang and own interpretation of particular rules. Remember pragmas? Just taking a piece of C code and compile it with another compiler is most likely not going to work.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline f1rmb

  • Regular Contributor
  • *
  • Posts: 180
  • Country: fr
Re: while loop in software
« Reply #163 on: December 21, 2014, 01:40:47 pm »
That is not going to work. Back in the old days every C compiler had it's own slang and own interpretation of particular rules. Remember pragmas? Just taking a piece of C code and compile it with another compiler is most likely not going to work.

Yeah #pragma :palm:
But it's preprocessor, compiler dependant.
Using specific compiler extensions is another story.
Anyway, I couldn't agree with anyone claiming that VB heaven and the programming language to learn, for obvious reasons.
So, sorry to bother, but I can't stay silent when I read such kind of thing.

« Last Edit: December 21, 2014, 05:29:23 pm by f1rmb »
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #164 on: December 21, 2014, 07:14:15 pm »
The OP doesn't specify if he is programming an MCU or some computer with more resources.

For MCUs, C is king, C++ on bigger MCUs and of course you always have assembler. There is nothing else and C++ is just a pig.

For procedural programming and repetitive tasks you need some form of while statement, you could implement it with a goto as well but it will loop either way.

MCUs are not big enough for functional programming like Erlang with high concurrency, Even using C++11 lambdas will give you a great deal of parallelism.

But functional programming is less efficient than imperative procedural, but allows a great deal of parallelization for multicore/multiprocessors or even in the virtual computing scene with nine 9's of uptime. As for memory pointers etc, Erlang for example is single assignment, you only assign a value to a variable once, so no one else can write on it, so there is no risk of competition for the same resource.

So unless we are targeting 100 core MCUs C is still king but at the moment it would be silly to get a power hungry multicore processor to replace the functionality of an MCU, I guess depending on the task at hand (computer vision, or other heavy parallel computing applications) you might need something like that.

As for blaming C as the cause of exploits, I doubt it, I don't see many servers running C, most likely is badly coded php that allows SQL injections. And that doesn't mean buffer overruns, it just means bad programming that would allow you to do a for * query.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #165 on: December 21, 2014, 07:18:18 pm »
As for blaming C as the cause of exploits, I doubt it, I don't see many servers running C, most likely is badly coded php that allows SQL injections. And that doesn't mean buffer overruns, it just means bad programming that would allow you to do a for * query.

PHP is a whole different class of bad... :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 #166 on: December 21, 2014, 07:39:46 pm »
For MCUs, C is king, C++ on bigger MCUs and of course you always have assembler. There is nothing else and C++ is just a pig.

I prefer C++ over C even for small MCUs. Some features such as namespaces static classes and references improves the program's organization and readability with virtually no additional runtime cost.

Even in the Arduino world C++ is the standard (e.g. Serial.prinln("Hello World")).
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #167 on: December 21, 2014, 08:04:22 pm »
For MCUs, C is king, C++ on bigger MCUs and of course you always have assembler. There is nothing else and C++ is just a pig.

I prefer C++ over C even for small MCUs. Some features such as namespaces static classes and references improves the program's organization and readability with virtually no additional runtime cost.

Even in the Arduino world C++ is the standard (e.g. Serial.prinln("Hello World")).

Agreed, and I speak from a pure C old fart perspective. My concern is though that others might not understand the impact of other langiage "features" as you do. Having said that, static namespaces can be dealt with by a half decent naming convention in C in the MCU world.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #168 on: December 21, 2014, 09:05:39 pm »
By small MCU I mean 2048 words of programming memory or less for example a PIC16 which is considered a mid range MCU by Microchip. But by today's standards I would consider it as a base core size.

But if you have 32K, then sure C++ will fit the bill, the resulting code will be 150% the C size and 3 times slower in general computing.

C++ is good for large projects but it has a lot of traps for young players. There are good C++ programmers out there, but the bad ones are the overwhelming majority. That is the reason why Linus won't allow C++ on his kernel.

Even if it's counter intuitive, C++ can produce more dangerous code than C that it's harder to spot.

That said, for the Arduino ecosystem it does make sense to use C++ because you have an object with methods that control that device, It's nicely encapsulated and you can derive classes for similar components (not sure if they do that since I never really did any Arduino coding other than some tests on the Intel Galileo).

In that aspect C++ is more versatile for a beginner, but that doesn't mean is better, more efficient or even more maintainable. If someone refers to C as a hammer, C++ is the sledge hammer chainsaw from Deadrising 3, powerful but dangerous at the same time.

And I use C++ at work and I find it very elegant, but we have good programmers and the bad ones are spotted fairly easily since we require code reviews.

 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #169 on: December 21, 2014, 09:07:57 pm »
But if you have 32K, then sure C++ will fit the bill, the resulting code will be 150% the C size and 3 times slower in general computing.

Demonstrably false. Any decent compiler, including GCC, has no problem switching to C++ and increasing the code size by all of a couple bytes. Then you pay for what you use - things like namespaces and overloading are free.
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #170 on: December 21, 2014, 09:23:25 pm »
But if you have 32K, then sure C++ will fit the bill, the resulting code will be 150% the C size and 3 times slower in general computing.

Demonstrably false. Any decent compiler, including GCC, has no problem switching to C++ and increasing the code size by all of a couple bytes. Then you pay for what you use - things like namespaces and overloading are free.

If that is all that you are going to use C++ for, then as Howardlong stated, you can use naming conventions to get the same result in C. After all that's all the name mangling does.

But if you are going to use the full feature set I stand by my assertion.
 

Offline Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #171 on: December 21, 2014, 09:40:09 pm »
As for blaming C as the cause of exploits, I doubt it, I don't see many servers running C, most likely is badly coded php that allows SQL injections. And that doesn't mean buffer overruns, it just means bad programming that would allow you to do a for * query.

I did mention SQL too (or rather the SQL interfaces we keep using). It's another one of those cases of needlessly relying on programmers not to screw up ... it's a symptom of the same disease.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #172 on: December 21, 2014, 10:13:28 pm »
By small MCU I mean 2048 words of programming memory or less for example a PIC16 which is considered a mid range MCU by Microchip. But by today's standards I would consider it as a base core size.

But if you have 32K, then sure C++ will fit the bill, the resulting code will be 150% the C size and 3 times slower in general computing.

C++ is good for large projects but it has a lot of traps for young players. There are good C++ programmers out there, but the bad ones are the overwhelming majority. That is the reason why Linus won't allow C++ on his kernel.

Even if it's counter intuitive, C++ can produce more dangerous code than C that it's harder to spot.

That said, for the Arduino ecosystem it does make sense to use C++ because you have an object with methods that control that device, It's nicely encapsulated and you can derive classes for similar components (not sure if they do that since I never really did any Arduino coding other than some tests on the Intel Galileo).

In that aspect C++ is more versatile for a beginner, but that doesn't mean is better, more efficient or even more maintainable. If someone refers to C as a hammer, C++ is the sledge hammer chainsaw from Deadrising 3, powerful but dangerous at the same time.

And I use C++ at work and I find it very elegant, but we have good programmers and the bad ones are spotted fairly easily since we require code reviews.

I can't argue with any of that!
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #173 on: December 21, 2014, 10:31:29 pm »
As for blaming C as the cause of exploits, I doubt it, I don't see many servers running C, most likely is badly coded php that allows SQL injections. And that doesn't mean buffer overruns, it just means bad programming that would allow you to do a for * query.

PHP is a whole different class of bad... :scared:

Given my hatred of C, it is nothing compared to my hatred of PHP.  We finally agree on something.

For MCUs, C is king, C++ on bigger MCUs and of course you always have assembler. There is nothing else and C++ is just a pig.

I prefer C++ over C even for small MCUs. Some features such as namespaces static classes and references improves the program's organization and readability with virtually no additional runtime cost.

Even in the Arduino world C++ is the standard (e.g. Serial.prinln("Hello World")).

Arduino is an odd mix of C and C++.  I'm actually mostly OK with C++ because it's object oriented.  PHP will never curry favor from me, OO or not, due to its completely aimless method/function naming and completely random syntax.
 
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #174 on: December 21, 2014, 10:43:02 pm »
Computers are supposed to aid us.  With C, the computer just gets in the way, lets you lay little traps that no one will notice for years, and almost aids developers in making mistakes.  My primary complaint about that is that NO ONE SEEMS TO CARE.  Virtually every C developer I've known, when I mention how easy common mistakes are, they respond with something like "yeah, so don't do that."  You're sitting at a computer which was partially DESIGNED to detect errors that humans are prone to make and we still rarely use them to detect errors that humans are prone to make, purely because we each have so much misplaced confidence in our own abilities. 

The result is that every new C developer makes these mistakes again and again, and we constantly hear about code that is vulnerable to buffer overflow or memcopy exploits or whatever the bug du jour is lately.

We could use the computer to aid us as C developers, yet we choose not to.  This is my complaint.  We are so full of ourselves to think if we just remember not to do a bad thing that no bad things will happen in our code.

So you are suggesting someone invents a utopian language that won't permit the programmer to make any mistakes, and yet gives the runtime performance as C? Sounds great, why don't you do it?  You'd certainly make a lot of money.

No, I'm suggesting that people not accept tradition as a good reason for anything.  There are a lot of silly mistakes that people make, and to take steps to avoid those mistakes in the future is time and effort well spent.  Yet, here we sit, with virtually the same C we had decades ago, with newbs making the same silly mistakes they made decades ago.

Again, I'm not proposing a Utopian language, I just see a lot of little things that could be easily made better, and no effort is spent on those small changes.

Here's a potential replacement for C on micros.
http://dlang.org/comparison.html
...
Yeah, but will anybody care to write a D compiler for ARM, for Atmel, for Freescale's  PowerPC (Esys) cores or even more obscure stuff (Infinion Tricore or Freescale eTPU)?
Writing/adapting a compiler for a specific core architecture is not an easy task. Optimization strategies differ, pipeline effects have to be considered and so on. Even between cores of the same family, the command set differs. There are even cores with two switchable instruction sets, dedicated SIMD or floating point engines with very specific implementations etc.
The only reason that we can develop for ARM and Atmel with freely available compilers is that C was and is of such importance that GCC was started as open source project.
Anyway, in industrial applications with safety to consider, you usually want to use a compiler which has certain certifications and guarantees to work around known errata of the supported cores.
This means though that some software vendor like BlueRiver and the likes is interested to develop that compiler for you - which they only do if there is enough demand for it.
And honestly, for the next ten years to come, the Demand for C/C++ will be much higher than for somewhat exotic languages like D or Rust or whatever.

So on a microcontroller it's not like on the PC where you can decide freely which language to choose for a project. In the end you kinda need to use C since there is simply no other (stable, robust, certified, performant) other compiler available. The only chance would be to use a higher level language or symbolic tool that creates C code which then needs to be compiled by the default C compiler. Problem is that this increases build time and makes it very hard to debug. Also chance of tool/compiler errors increases.

I don't know if someone will care to write a compiler for D for micros.  Probably not.  Is it really that much of a sin to wish for a better environment?  Fucks sake.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #175 on: December 21, 2014, 11:27:49 pm »
If that is all that you are going to use C++ for, then as Howardlong stated, you can use naming conventions to get the same result in C. After all that's all the name mangling does.

When you program in C++, do you use naming conventions instead of namespaces? Let me guess, no, because namespaces are more intuitive and are cheap in runtime resources. What about C++ references, do you also avoid them when you program in C++? No, because in some instances there are more intuitive than pointers and again have insignificant runtime cost.  And we keep going with other C++ features such as overloading and others. The bottom line is that C++ has extensions of C that are useful and cheap, even in resource sensitive applications.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #176 on: December 22, 2014, 12:02:00 am »
As for blaming C as the cause of exploits, I doubt it, I don't see many servers running C, most likely is badly coded php that allows SQL injections. And that doesn't mean buffer overruns, it just means bad programming that would allow you to do a for * query.

All kinds of server run C in the form of lib*.so or lib*.dll or whatever that is used by the language that the application coding was actually done in or the server the applications run on.  This is how Heartbleed had such a huge surface attack area: libSSL.so.

In Perl, there is the concept of "taint checking."  You can force a Perl script to disallow the use of user input before it has been "checked" via a regular expression.  That was added well over a decade ago, it is a simple thing, and yet no other language (that I know of) utilizes taint checking.  Taint checking alone, (if not worked around by a developer) would eliminate SQL injection, because it would force the developer to validate the query string against a regex.  Maybe a regex isn't the best vehicle for this, but I hope my point is coming across. We could add things to stop common bugs, but we continue to rely on the developer to remember more and more and more, when the tooling could (and arguably should) handle a great deal of it.
 

Offline Marco

  • Super Contributor
  • ***
  • Posts: 6687
  • Country: nl
Re: while loop in software
« Reply #177 on: December 22, 2014, 01:47:21 am »
PHP is a whole different class of bad... :scared:

The latest Drupal SNAFU is pretty funny ... write a framework to separate arguments from commands (with escape character filtering of the arguments being done by the framework) to avoid SQL injection ... then have the code interpret the arguments as something other than pure strings. Good show.
« Last Edit: December 22, 2014, 01:49:56 am by Marco »
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #178 on: December 22, 2014, 03:32:34 am »
Quote
Stick to pure C/C++ (libc and friends), write some abstraction layer, and you'll have to only (re)write the platform specific sections.
yeah; right.  I'm looking at porting some code from the relevant era, and it has separate Make targets for BSD, SYSV, Ultrix, AIX, Next, HPUX, and more.  And I was serious about field days caused by new compiler versions; I think it was going from 2.95 to 3.x where gcc decided that string constants could no longer include newlines (hundreds of files with built-in but not normally compiled "full description" fields for error messages.  Sigh.)  Even with up-to-date versions of all the compilers involved, you can find queries on AVRFreaks and equivalent about how to rewrite C from Codevision to Imagesoft to gcc to mikro-C.   It's not the code that has been very carefully written by experts cognizant in the subtleties of portability between a dozen environments that gets you, it's the code written in an entirely reasonable way by people who are less aware (and that's a lot of code.)
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #179 on: December 22, 2014, 04:01:11 am »
portability is a theoritical ideal. in practice its not that ideal...
1) code have to be bloated with #if switch and you cant think what system you are going to target in the future
2) new thoughts or condition in the future will change the language spec and mostly inevitably will screw past spec for portability. basics is good example i know (even c/c++) but i'll stick to one revelation and forget portability, so long my app is working and aiding me in my system. its manmade anyway, man makes mistake, so there's nothing wrong sticking with older revelation :P
3) even if the old code are portable, do you care to recompile 20yrs of app code for your new modern app? no! at most you'll use it as reference. even big companies make a complete rewrite in new version from the older version just few not so old yrs ago.

i heard some people saying PHP is bad, then what option do i have for programming web interface? i already bought the PHP book yet to be learnt :|
« Last Edit: December 22, 2014, 04:03:47 am by Mechatrommer »
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 theoldwizard1

  • Regular Contributor
  • *
  • Posts: 171
Re: while loop in software
« Reply #180 on: December 22, 2014, 05:32:25 am »
Ahh, you youngsters !

All modern "structured" languages are actually decedents of ALGOL !

First language to have "free form" input,  "blocks" (BEGIN ... END), and nested (reenterant) functions !  Nested function required the first use on a "stack" for parameter passing and return addresses.  It also introduced the Bacus-Naur Form, a definitive method of specifying computer languages.

It was extensively used by Burroughs (yeah, who?) "large systems" starting in 1961.  They even had the concept of data memory versus program memory that were protected from each other (GOSH, no chance of executing off of the end of the stack or memory space not allocated to you process  !)
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #181 on: December 22, 2014, 05:53:08 am »
Really? if you want to go to the past, not that it's going to be MCU friendly anyways, at least talk about Fortran that predates Algol and actually was used and taught to EEE students.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #182 on: December 23, 2014, 02:35:30 pm »
...although I'm not sure I'd rate Fortran particularly highly as promoting structured programming.

I never have really figured out the popularity of Fortran, maybe it's because the "programmer" can choose to ignore machine limitations much of the time and concentrate on enormous array based processing, with the compiler desperately papering over the cracks.

Algol 60 was my first programming language, using paper tape for input and output. Back in the 70s I still remember being taught GOTO in one of the first exercises. Oh dear!
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #183 on: December 23, 2014, 02:56:09 pm »
Really? if you want to go to the past, not that it's going to be MCU friendly anyways, at least talk about Fortran that predates Algol and actually was used and taught to EEE students.

Apparently it's still alive  http://en.wikipedia.org/wiki/Fortran#Fortran_2015 , just like Aramaic.
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #184 on: December 23, 2014, 07:25:10 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.

I agree, designing well performing queries for large databases is a very complex task, in general my preferred approach is to have devs work on a database with random data using approximately the same distribution and size as any enterprise would potentially generate. That results is much less implementation issues than working on a 10 row per table database during dev. Also the whole working on a several thousand table DB needs to be strictly controlled, as in tracking all changes for client updates and in case something goes bad, you need to be able to roll it back.

The SQL server is often a performance bottle neck in a large system, as in, you can cluster it, but still it needs to be synchronized. And you need to be able to do backups while keeping it online and in more extreme cases you need to be able to fail over to a 2nd set of servers in case of emergencies. Much easier to scale clients and middle tier.

The code standard thing is more of a preference I stick to based on experience (I'll do the same for any SQL review). When you deal with millions of lines of code and you need everyone to be able to dive in a fix something, often written by someone else, and preferably without creating any regression bugs, part of my job is to make their job as easy as possible. It's really not an issue in a professional environment.

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

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #185 on: December 24, 2014, 03:16:35 am »
Quote
at least talk about Fortran
I don't think that anyone considers (historical) ForTran to have been a "Structured Programming Language."
It's interesting that Algol managed to be the parent of structured programming, without being (AFAIK) much of a commercial success itself.  Although I guess that in those days, success in academia WAS indeed "Success."
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #186 on: December 24, 2014, 08:30:55 pm »
The SQL server is often a performance bottle neck in a large system, as in, you can cluster it, but still it needs to be synchronized. And you need to be able to do backups while keeping it online and in more extreme cases you need to be able to fail over to a 2nd set of servers in case of emergencies. Much easier to scale clients and middle tier.

Clustering in a SQL Server context has nothing to do with performance or scalability, it is for high availability alone, in an active/passive configuration per instance, and even then it'll only work across locally connected nodes, so if you have a site outage you're buggered anyway. Somehow Microsoft managed to sell SQL Server clustering to an awful lot of folk, and at a serious premium too both in terms of software licensing and the hardware required to support it. Only when it was too late did many managers realise the fundamental flaws in it.

While people talk a out active/active clustering on SQL Server, it will be on separate instances, only one node on each instance is ever active at one time. There is no load balancing per the classical definition. To my mind this was one of the more underhand marketing bullshits to come out of Microsoft.

As you say, doing 24/7 on a transactional SQL Server implementation is not easy, especially if you also want high availability. It is possible these days at the database engine level, but in the not too distant past, it had to be done by implementation specific methods which were very hard to maintain.

« Last Edit: December 25, 2014, 09:43:20 am by Howardlong »
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #187 on: December 25, 2014, 08:42:15 pm »
The SQL server is often a performance bottle neck in a large system, as in, you can cluster it, but still it needs to be synchronized. And you need to be able to do backups while keeping it online and in more extreme cases you need to be able to fail over to a 2nd set of servers in case of emergencies. Much easier to scale clients and middle tier.

Clustering in a SQL Server context has nothing to do with performance or scalability, it is for high availability alone, in an active/passive configuration per instance, and even then it'll only work across locally connected nodes, so if you have a site outage you're buggered anyway. Somehow Microsoft managed to sell SQL Server clustering to an awful lot of folk, and at a serious premium too both in terms of software licensing and the hardware required to support it. Only when it was too late did many managers realise the fundamental flaws in it.

While people talk a out active/active clustering on SQL Server, it will be on separate instances, only one node on each instance is ever active at one time. There is no load balancing per the classical definition. To my mind this was one of the more underhand marketing bullshits to come out of Microsoft.

As you say, doing 24/7 on a transactional SQL Server implementation is not easy, especially if you also want high availability. It is possible these days at the database engine level, but in the not too distant past, it had to be done by implementation specific methods which were very hard to maintain.

Sure, the most common, simple active/passive single instance cluster, is purely for redundancy. But the active - active can improve performance, in the case where your system is designed to run on multiple databases, as in you can balance the load across multiple servers/databases and in case of hardware failure (or maintenance) you can run all the instances on a single node. However you do need to evaluate the added cost of distributed transactions as you are likely to need to maintain some level of data integrity across these databases. But then again, it's common to have distributed transactions including message queues, file systems and databases across a number of server clusters in large systems.

Anyway, while for my part interesting and happy to exchange real experience with large system architecture options, I think we might be getting into a pissing contest here :) Probably not much related to uC and FPGA programming.

Edit: Merry Christmas :)
« Last Edit: December 26, 2014, 03:10:41 am by jaxbird »
Analog Discovery Projects: http://www.thestuffmade.com
Youtube random project videos: https://www.youtube.com/user/TheStuffMade
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #188 on: December 26, 2014, 08:35:51 am »
Agreed, merry Christmas to you too.

Cheers!
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11518
  • Country: my
  • reassessing directives...
Re: while loop in software
« Reply #189 on: December 26, 2014, 01:01:47 pm »
christ was not born 25dec
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 jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #190 on: December 26, 2014, 01:17:28 pm »
christ was not born 25dec

True, but these days, in the western part of the world Christmas less of a religious event and more about a tradition being nice to everyone and sharing a moment of joy, happiness and celebration with family and friends. I'm sure you have similar events in your part of the world :) if not, you should adapt the spirit of Christmas.



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

Offline paulie

  • Frequent Contributor
  • **
  • !
  • Posts: 849
  • Country: us
Re: while loop in software
« Reply #191 on: December 26, 2014, 01:23:50 pm »
christ was not born 25dec

Also unlikely he or any relation was involved with creation of the space time continuum or even the homo sapien species. I'm not saying impossible, just unlikely.

BTW It's very important to keep important threads like this on topic.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #192 on: December 26, 2014, 04:25:27 pm »
christ was not born 25dec

... which brings us back to the should-I-use-the-while-loop dilemma, what would Christ do?
 

Offline jaxbird

  • Frequent Contributor
  • **
  • Posts: 778
  • Country: 00
Re: while loop in software
« Reply #193 on: December 26, 2014, 04:52:40 pm »
... which brings us back to the should-I-use-the-while-loop dilemma, what would Christ do?

And not to underestimate the existential question of what is the condition used in the while loop of the Universe?

while (forever?)
{
  Expand();
}
otherwise
{
  Contract();
}

So is the universe as we know it just a poorly coded expansion loop or are the Hindis correct that it was meant to be an infinite loop of expansion and contraction?

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

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #194 on: December 27, 2014, 01:36:23 am »
Quote
what would Christ do?
God writes in LISP code: 
(I especially like the description of assembler...)
 

Offline jpelczar

  • Contributor
  • Posts: 36
  • Country: kr
Re: while loop in software
« Reply #195 on: December 27, 2014, 01:59:05 am »
christ was not born 25dec

... which brings us back to the should-I-use-the-while-loop dilemma, what would Christ do?

Yes. By all means - use it. If someone says that for is faster than while (or *x++ is faster than a=*x; x++;, or goto is slow), then he must have spent last 10 years under a rock or is high on cocaine. If some compiler produces non-optimized code in either case, it should be shredded, thrown into a volcano and forgotten about - no sane compiler these days cares about this and it means you are using worthless piece of crap, which would probably be acceptable during Atari 2600 era. Code is expanded into various machine and language independent forms and optimized from there. Modern compilers have optimizers. If your program works incorrectly when you turn optimization on - it means your program has a bug. Shitty code with loops like while(i-->0); do make "delay" is reduced to nothing. Expressions without side effects are mercilessly exterminated. If something can be evaluated during compilation time (even function calls), they're removed and replaced with the result.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #196 on: December 27, 2014, 03:27:31 am »
...Shitty code with loops like while(i-->0); do make "delay" is reduced to nothing.

Not if if i is volatile, right?


If something can be evaluated during compilation time (even function calls), they're removed and replaced with the result.

As a matter of style I avoid #define whenever possible (which is almost always the case) and leave it to the compiler to optimize it. For example

const int kSize = 10*3;   // rather than #define SIZE (10*3)
...
char buffer[kSize];


 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6458
  • Country: nl
Re: while loop in software
« Reply #197 on: December 27, 2014, 09:25:40 am »
const int kSize = 10*3;   // rather than #define SIZE (10*3)
...
char buffer[kSize];
I rather have a long #define list in the header file than a long list of consts in the c file but that is a choice. Most important for me is that the programmer chooses a relevant name for the value instead of larding his code with magic numbers.
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #198 on: December 27, 2014, 10:21:31 am »
As a matter of style I avoid #define whenever possible (which is almost always the case) and leave it to the compiler to optimize it. For example

const int kSize = 10*3;   // rather than #define SIZE (10*3)
...
char buffer[kSize];
This creates worse code than the define since the compiler can't replace the constant variable by a constant offset.
E.g. if this was a struct array, the multiplication with the size of struct can't be optimized.
The qualifier "constant" just means that the value doesn't change during runtime. It doesn't mean it's fixed during compile time.
This is heavily used in embedded projects to exchange only the constants without touching the code ("calibration").
-> Using defines is a perfectly valid way of optimization in C and not bad style at all if you use it in a sensible way.
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #199 on: December 27, 2014, 02:20:53 pm »
The qualifier "constant" just means that the value doesn't change during runtime. It doesn't mean it's fixed during compile time.

Why it's not fixed value at compile time? What other values can it has?
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #200 on: December 27, 2014, 02:31:49 pm »
The qualifier "constant" just means that the value doesn't change during runtime. It doesn't mean it's fixed during compile time.

Why it's not fixed value at compile time? What other values can it has?

42?

Code: [Select]
* (int*) &kSize = 42;

May or may not work, depending on platform, of course. :P
« Last Edit: December 27, 2014, 02:33:41 pm by c4757p »
No longer active here - try the IRC channel if you just can't be without me :)
 

Offline hamdi.tn

  • Frequent Contributor
  • **
  • Posts: 623
  • Country: tn
Re: while loop in software
« Reply #201 on: December 27, 2014, 02:38:03 pm »
while (1)
  {
     keeptalkingaboutwhileloop();
  }
 :-DD
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #202 on: December 27, 2014, 03:15:19 pm »
Why it's not fixed value at compile time? What other values can it has?
I already answered the question, but I can do it again: a constant variable resides in a constant memory section. In an embedded projects, this is (Flash-)ROM. So you can exchange the ROM which contains these constants and get a different behavior without recompiling. This is how different calibration variants are handled in thousands of embedded projects in the last 15 years or so. If the compiler would treat a precompiler constant (define) exactly like a constant variable, this widespread concept would no work.
Besides, a global (non-static) variable with the qualifier const can't be simply removed as it's global.
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #203 on: December 27, 2014, 04:05:48 pm »
I already answered the question, but I can do it again: a constant variable resides in a constant memory section. In an embedded projects, this is (Flash-)ROM. So you can exchange the ROM which contains these constants and get a different behavior without recompiling. This is how different calibration variants are handled in thousands of embedded projects in the last 15 years or so. If the compiler would treat a precompiler constant (define) exactly like a constant variable, this widespread concept would no work.
Besides, a global (non-static) variable with the qualifier const can't be simply removed as it's global.

I just tested it with the ARM gcc that comes with the LPCXpresso and the const it is optimized out beautifully as expected.

Case 1:
Code: [Select]
const int kkkk = 7;
volatile int jjjj = 0;

int main(void) {
  for (;;) {
    jjjj += kkkk;
  }
}

kkkk doesn't appear in the memory map and jjjj is incremented by the literal 7.


Case 2:
Code: [Select]
const volatile int kkkk = 7;
volatile int jjjj = 0;

int main(void) {
  for (;;) {
    jjjj += kkkk;
  }
}

kkkk appears in the memory map and jjjj is incremented by a value from memory.

The advantage of real consts over #defines is that they are part of the language, subject to scoping, namespaces, typing, etc. Same goes for inlined functions over #define based logic.




« Last Edit: December 27, 2014, 04:34:22 pm by zapta »
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #204 on: December 27, 2014, 04:24:15 pm »
Case 1:
Code: [Select]
const int kkkk = 7;
volatile int jjjj = 0;

int main(void) {
  for (;;) {
    jjjj += 2*kkkk;
  }
}
kkkk doesn't appear in the memory map and jjjj is incremented by the literal 7.
if so, this is a compiler bug, as it should be incremented by 14, shouldn't it?

The advantage of real consts over #defines is that they are part of the language, subject to scoping, namespaces, typing, etc. Same goes for inlined functions over #define based logic.
I wouldn't argue on this. Yet the behavior you observed is not the behavior I ever observed with any embedded commercial compiler (Keil, Diab, Windriver etc.) I ever worked with.
Guess there are setting for this, but the use of constants as calibration constant is so intensively used that I would have assumed that no embedded compiler would apply this kind of optimization by default.
Maybe a GCC thing since it was developed for desktop applications.
Besides: If a compiler removes a variable because it thinks it's futile, it should at least throw a warning.
In my experience, a global variable or function is never removed unless the whole module (*.o) is removed by the linker since not a single symbol within is referenced.
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #205 on: December 27, 2014, 04:44:08 pm »
if so, this is a compiler bug, as it should be incremented by 14, shouldn't it?

Good catch. I posted the wrong version of Case 1 (now fixed).

Besides: If a compiler removes a variable because it thinks it's futile, it should at least throw a warning.
In my experience, a global variable or function is never removed unless the whole module (*.o) is removed by the linker since not a single symbol within is referenced.

It's semantically correct, not futile at all, but it doesn't mean that it is required in the mapping to an efficient machine code (such as loops that are inlined, variables that lives in regs or two variables that don't live at the same time and are assigned to the same memory location).

BTW, would be surprised if you your compiler/linker eliminates stuff in .o file granularity. You may end up with more linked library functions that you actually used.

Check jpelczar's post here (and ignore the salty language) https://www.eevblog.com/forum/microcontrollers/while-loop-in-software/msg575284/#msg575284
« Last Edit: December 27, 2014, 04:45:52 pm by zapta »
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #206 on: December 27, 2014, 05:32:30 pm »
It's semantically correct, not futile at all, but it doesn't mean that it is required in the mapping to an efficient machine code (such as loops that are inlined, variables that lives in regs or two variables that don't live at the same time and are assigned to the same memory location).
Yeah, but it's a global symbol that could be referenced by another C module. Hence a C compiler should never remove unused globals, only the linker should be able to do that since only at the linker stage, it's known if the symbol is referenced on a global scope.
Probably this is what happens here in a two stage process:
Firstly the compiler replaces the access to a constant variable with an immediate value inside the main module. Secondly, the linker detects that the variable is also not referenced externally, so it removes it completely.
This is a rather aggressive optimization strategy though. And surely not one that you can expect to exist in any project you'll ever work on.

BTW, would be surprised if you your compiler/linker eliminates stuff in .o file granularity. You may end up with more linked library functions that you actually used.
Well, it's even worse. In all the 32bit projects I worked on in the last years (mainly Freescale eSys and Infineon Tricore), the linker can even keep the whole module if nothing from it is referenced at all. This is said to happen because of debug references in the debug (Dwarf) part of the created (Elf) program. The only known workaround is to use the archiver to create a library (*.a) from the objects. Then a completely unreferenced module is usually removed.

Anyway, even if this works as you suspect in your project environment, there is no guarantee that it would in another project with a different compiler/target or mainly other compiler/linker (optimization) settings. For sure, it would not be optimized in the projects that I work on for a living, so if I had to review a piece of your code, this use of const variables be marked as finding ("avoid waste of ROM or runtime resources").
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #207 on: December 27, 2014, 06:01:18 pm »
This is a rather aggressive optimization strategy though. And surely not one that you can expect to exist in any project you'll ever work on.

I am using gcc for a wide range of applications, from 8 bit MCUs to large distributed computation and server programs that run on thousands of cores and I always expect this level of optimization.

For sure, it would not be optimized in the projects that I work on for a living, so if I had to review a piece of your code, this use of const variables be marked as finding ("avoid waste of ROM or runtime resources").

In this case, every Arduino kiddie is using a better C/C++ compiler than you.  ;-)

BTW, by your example of configuration values, this expression should be computed at runtime. If your compiler really does it at runtime I would seriously look for a better compiler.

Code: [Select]
const int config1 = 100;
const int config2 = 5;
...
int i = config1 / config2;
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #208 on: December 27, 2014, 07:11:45 pm »
In this case, every Arduino kiddie is using a better C/C++ compiler than you.  ;-)
Even if you defined "better" as "using more aggressive optimization" that would be disputable to say the least.
BTW: "You" (as addressed in the quote) in this case is a multi-national company with thousands of SW developers.

BTW, by your example of configuration values, this expression should be computed at runtime. If your compiler really does it at runtime I would seriously look for a better compiler.
As I stated twice, not optimizing constant variables is the calibration concept used in the automobile industry since the beginning of microcontroller based control units (like for >20 years or so).
I would suspect though that it's also used in other branches.
Even if there would be GCC versions for the processors used, it would most probably never be shortlisted for a couple of reasons.

Even if you think that Arduino or freely available GCC derivates are the industry standard, just keep in mind that one day you might end in a project where your understanding of good style is not shared and code like yours will not pass a review.
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #209 on: December 27, 2014, 07:40:53 pm »
0xdeadbeef, will the computer that you are using compute this divide operation at runtime?

Code: [Select]
const int config1 = 100;
const int config2 = 5;
...
int i = config1 / config2;
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #210 on: December 27, 2014, 07:59:15 pm »
0xdeadbeef, will the computer that you are using compute this divide operation at runtime?

Code: [Select]
const int config1 = 100;
const int config2 = 5;
...
int i = config1 / config2;

"Computer" is a strange term and I answered this already several times but again: the calibration concept used in all the microcontroller projects I know in the three companies I worked for (exact counting is difficult) in the last nearly 16 years forbids that the compiler removes this division. This division must be done during runtime else it would be impossible to have different calibration variants - which just differ in the flash section where these constants ares stored.
So it is not valid to assume that this is something that a good compiler must remove.

As a side note, maybe read through this:
http://en.wikipedia.org/wiki/Const_%28computer_programming%29#Consequences

In a nutshell: const doesn't mean that it's impossible to write to a const (if the memory section is physically writable, this is always possible though pointer magic).
The const qualifier is just meant to tell the compiler that the programmer doesn't intend to change the value. This allows for certain optimization like keeping the value inside a register.
Regarding variables, "const" is somewhat the opposite of "volatile" since volatile means that the compiler must never read/write a register instead of a variable.
Trying is the first step towards failure - Homer J. Simpson
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #211 on: December 27, 2014, 08:24:00 pm »
This division must be done during runtime else it would be impossible to have different calibration variants - which just differ in the flash section where these constants ares stored.
So it is not valid to assume that this is something that a good compiler must remove.

That's what the 'volatile' keyword is for.
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #212 on: December 27, 2014, 09:57:17 pm »
That's what the 'volatile' keyword is for.
Not really. I already described what the volatile qualifier means for variables.
Anyway, if you look at properly written C code, you'll see that volatile on variables is not used to avoid them being removed but to force the compiler to always use the variable in memory instead of local copies.
This is needed if the variable is written/read in different interrupt/task levels to avoid incoherency. Also peripheral registers are volatile to avoid read to / writing to temporary copies.
Obviously, declaring a variable volatile also means that its memory location must not be removed, but that's not the main intention.
Trying is the first step towards failure - Homer J. Simpson
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #213 on: December 27, 2014, 10:19:16 pm »
This thread is volatile as we don't know the state at any given point in time so we must not cache it and spend extra cycles fetching its contents that no longer have anything to do with while loops.
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #214 on: December 27, 2014, 11:10:26 pm »
Honestly, this thread was doomed from its very start ;)
Trying is the first step towards failure - Homer J. Simpson
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #215 on: December 28, 2014, 12:41:09 am »
Quote
it would be impossible to have different calibration variants
I understand what you want, and I sure hope that whatever compiler you use (or the infrastructure you have added) has keyword phrases that enforce that behavior ("extern volatile const"?  "__pragma__(calibration)"?), because "calibration constant" are for sure well outside the language definition/specification, and compile-time evaluation of constant expressions is an important and common part of reasonable optimization.   (and oh, what a nightmare to debug, should the compile decide that it can optimize your constants away in addition, but not in multiplication...)

It is the sort of compiler behavior that I would be really reluctant to count on! 
(not all compilers put "const" variables in flash in the first place.  Especially on harvard architecture machines.)

For actual constants, "static const" should be better than just "const"...
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #216 on: December 28, 2014, 02:19:25 am »
I understand what you want, and I sure hope that whatever compiler you use (or the infrastructure you have added) has keyword phrases that enforce that behavior ("extern volatile const"?  "__pragma__(calibration)"?), because "calibration constant" are for sure well outside the language definition/specification, and compile-time evaluation of constant expressions is an important and common part of reasonable optimization.   
I'm not aware of any specific trickery that had to be done to get it right and I think I already looked at all the places where it could have been applied.
Then again, in a large company, you have dedicated departments just for the compiler setup. So I wouldn't rule out that there is something I always overlooked.
Anyway, stuff like this is always discussed with the compiler vendor. It's not like trying and hoping the best if that's your concern. One of the reasons why a vanilla GCC is never on the short list.

Quote from: westfw
(and oh, what a nightmare to debug, should the compile decide that it can optimize your constants away in addition, but not in multiplication...)
I was involved in all kind of unpleasant debugging stuff, but never saw a behavior like this.
BTW: if you think that's tricky then wait until you map your calibration ROM to RAM though MMU or SDA pointer trickery, write a new value to RAM and observe how the CPU takes some constants from RAM but some still from ROM due to cache lines not being flushed. That is hard to debug.

Quote from: westfw
It is the sort of compiler behavior that I would be really reluctant to count on! 
Then I guess you shouldn't drive any car built after 1980 ;)

Quote from: westfw
(not all compilers put "const" variables in flash in the first place.  Especially on harvard architecture machines.)
Well, assuming we're talking about microcontrollers, the constants are obviously always in flash. The only question is if they are then copied to RAM or accessed from Flash.
Harvard architecture doesn't really have much to do with this. It's just that the compiler needs to create different opcodes to read from ROM and RAM but a good compiler hides that from you.
E.g. at the beginning of the century/millenium, the 1st version of AVR-GCC was not able to fetch constants from flash due to other opcodes for reading from flash, so you either had to read from the RAM copy
or use specific intrinsic commands. At the same time, commercial compilers could already do this without workarounds.
Anyway, in the projects I worked on, this is just a matter of locator setup and maybe runtime initialization (which we usually do on our own anyway).
Trying is the first step towards failure - Homer J. Simpson
 

Offline Dinsdale

  • Regular Contributor
  • *
  • Posts: 77
  • Country: us
    • pretzelogic
Re: while loop in software
« Reply #217 on: December 28, 2014, 03:43:13 am »
Never use a while loop. While loops are current controlled. A for loop is voltage controlled. Use those.
This can't be happening.
 

Offline jpelczar

  • Contributor
  • Posts: 36
  • Country: kr
Re: while loop in software
« Reply #218 on: December 28, 2014, 04:06:31 am »
...Shitty code with loops like while(i-->0); do make "delay" is reduced to nothing.

Not if if i is volatile, right?

Yes, but IMO it's better to put

Code: [Select]
while(i-->0) __asm__ __volatile__("");

This will produce MUCH better code as compiler will not generate unneeded loads/stores for i.

For multithreading/multiprocessing - instead of volatile on modern CPUs (like Cortex A15 MPCore, A12, BigLittle, etc.) I use either assembly code (ldrex/strex) or compiler's atomic operations (#include <atomic>) if memory operations require ordering, but the code really depends on the use case. Avoid volatile at all cost, except for memory mapped I/O. Sometimes I see programmers use volatile because they don't have knowledge to fix their shit, and their code works only because optimizer doesn't do something with the code.


 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #219 on: December 28, 2014, 04:21:31 am »
Never use a while loop. While loops are current controlled. A for loop is voltage controlled. Use those.

Not if you are currently using it :)
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #220 on: December 28, 2014, 10:17:32 am »
Quote
assuming we're talking about microcontrollers, the constants are obviously always in flash.
You mean you WANT the constants to be in flash.  For instance, avr-gcc would happily put "const" variables in RAM (copied from flash at startup if they're initialized) and still treat them as "const" at the compiler level.  As you allude, on a microprocessor system, the compiler isn't going to have any idea which memory regions are flash (if there are any), and which are RAM (or ROM.)  On an x86, PPC, or ARM9 system (and many DSPs), "const" still has meaning as compile semantics, but you'll certainly have to go to extra effort if you really want some constants stored in a particular section of  a particular type of memory.

I'll have to admit to not knowing anything about automotive software methodology.  I'm a little surprised that calibration  constants aren't required to be in separate chips with well defined high level APIs protecting them...
 

Offline 0xdeadbeef

  • Super Contributor
  • ***
  • Posts: 1570
  • Country: de
Re: while loop in software
« Reply #221 on: December 28, 2014, 10:31:04 am »
You mean you WANT the constants to be in flash.  For instance, avr-gcc would happily put "const" variables in RAM (copied from flash at startup if they're initialized) and still treat them as "const" at the compiler level.
Notice something? Then just re-read what I wrote.

Quote from: westfw
I'll have to admit to not knowing anything about automotive software methodology.  I'm a little surprised that calibration  constants aren't required to be in separate chips with well defined high level APIs protecting them...
Not even in the times when the program was stored in EEPROM, they were in a separate "chip". They are located in a separate flash segment, so you can reprogram them independently.
Indeed, during development the mechanical engineers responsible for specific engine behavior change the calibration data during runtime by using tools that write to calibration RAM and the CPU switches between using constants from ROM or RAM (address line or SDA register trickery, specific overlay areas, nowadays mostly via MMU).
Trying is the first step towards failure - Homer J. Simpson
 

Offline Dinsdale

  • Regular Contributor
  • *
  • Posts: 77
  • Country: us
    • pretzelogic
Re: while loop in software
« Reply #222 on: December 28, 2014, 12:56:02 pm »
Quote
Not if you are currently using it
Doh! Of course, you are correct. I see that you have a lot of potential.
This can't be happening.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #223 on: December 28, 2014, 03:13:01 pm »
Doh! Of course, you are correct. I see that you have a lot of potential.
Good one  :-+
I'm glad that you didn't go into hysteresis, you are unlike others that get all saturated in these matters.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #224 on: December 28, 2014, 05:21:29 pm »
There are currently lots of potential differences on this thread. I don't know watt's going on, but susceptance to such behaviour should be met with resistance. Too much reactance going on IMHO.
 

Offline paulie

  • Frequent Contributor
  • **
  • !
  • Posts: 849
  • Country: us
Re: while loop in software
« Reply #225 on: December 28, 2014, 07:30:54 pm »
...
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #226 on: December 28, 2014, 07:36:05 pm »
Back to the topic, while loops are dangerous:

 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #227 on: December 28, 2014, 09:26:55 pm »
Everything here, concurrently interacting control loops with multiple entry and exit points, cats (for Dave) and frickin' lasers.

 

Offline old greggTopic starter

  • Regular Contributor
  • *
  • Posts: 130
  • Country: 00
Re: while loop in software
« Reply #228 on: December 28, 2014, 10:46:10 pm »
man I didn't expect so many pages. Looks like it was actually a good question.

thanks a lot for all the answers. I still have some pages left to read.
 

Offline Dinsdale

  • Regular Contributor
  • *
  • Posts: 77
  • Country: us
    • pretzelogic
Re: while loop in software
« Reply #229 on: December 28, 2014, 11:21:48 pm »
I actually enjoyed the diversion into some of the C specific issues that were discussed. It's too bad all that will become lost within the topic title. I didn't really intend to side-track those.
This can't be happening.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #230 on: January 04, 2015, 03:04:09 pm »
Not to resurrect the argument I started, but if there is anyone who doesn't understand what I was getting at, and WANTS TO, here's what I was trying to say, stated far better than I could have, in the first 15 minutes of this video: http://youtu.be/ca0DWaV9uNc
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: while loop in software
« Reply #231 on: January 04, 2015, 03:41:29 pm »
Thanks for that video. That laugh @07:25 is very telling and well timed. ;D
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #232 on: January 04, 2015, 04:21:30 pm »
Not to resurrect the argument I started, but if there is anyone who doesn't understand what I was getting at, and WANTS TO, here's what I was trying to say, stated far better than I could have, in the first 15 minutes of this video: http://youtu.be/ca0DWaV9uNc

That's guy is full of himself. I stopped at the 2:30 mark. But I think I know what you mean.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #233 on: January 04, 2015, 10:14:52 pm »
He made plenty of self deprecating remarks that would suggest he was not full of himself. Starting with emphasising he was an "academic" computer scientist.

From here he seemed to be the i-am-special-and want-attention kind of high maintenance presenter that doesn't get to the point.

Anyway, I get your point that computers could do more for us and that other programming paradigms can be more productive. We are definitely not at the end of the road.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #234 on: January 05, 2015, 03:31:40 am »
He's a college professor and has found a way to make his lectures penetrate the mind.

Everyone has something annoying.  Some wear it close, some put it out there and use it, like this guy.  Whatevs.  He's a hell of a lot smarter than me, so I'll put up with it in order to learn.
 

Offline Helix70

  • Supporter
  • ****
  • Posts: 289
  • Country: au
  • VK4JNA
Re: while loop in software
« Reply #235 on: January 05, 2015, 03:57:23 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.

Hmm, actually, this has a place in defensive programming, but for the test of equality.

Consider

if (x == 1)

A common typo is

if (x = 1)

which compiles without warning (on most compilers I use anyway). This code does something totally different and usually is undesired.

If you change this to:

if (1 == x)

instead, the typo

if (1 = x)

declares an error, as you cannot assign x to a constant. So once you get into this habit,

if (0 < x)

is a natural extension, and good practice to reducing coding errors.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7799
  • Country: us
  • adieu
Re: while loop in software
« Reply #236 on: January 05, 2015, 03:59:04 am »
I mentioned this already; it was summarily ignored.
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 #237 on: January 05, 2015, 04:02:54 am »
He's a college professor and has found a way to make his lectures penetrate the mind.

Everyone has something annoying.  Some wear it close, some put it out there and use it, like this guy.  Whatevs.  He's a hell of a lot smarter than me, so I'll put up with it in order to learn.

No problem. He is a free man and can behave the way he likes. He doesn't owe me a thing.
 

Offline Helix70

  • Supporter
  • ****
  • Posts: 289
  • Country: au
  • VK4JNA
Re: while loop in software
« Reply #238 on: January 05, 2015, 04:55:24 am »
I mentioned this already; it was summarily ignored.

Oh, sorry. Replied before reading the whole thread. Must try and keep up to date. Consider my post a +1 then :)
 

Offline Helix70

  • Supporter
  • ****
  • Posts: 289
  • Country: au
  • VK4JNA
Re: while loop in software
« Reply #239 on: January 05, 2015, 05:12:33 am »
Let's leave it here I don't think we are getting anywhere.

But if you ever get a real job with a large corp, you might be surprised to find there are strict standards and unless you comply, your work will be rejected.

I do believe you can see the benefits and logic in adhering to a standardized style opposed to everyone exercising individual styles.

I have a real job with a huge multi national corp. Thank the stars that improvements to code reliability are encouraged by it.
 

Online Jeroen3

  • Super Contributor
  • ***
  • Posts: 4065
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: while loop in software
« Reply #240 on: January 05, 2015, 07:18:56 am »
I watched his video. He made some interesting points.

The pile of rubbish stacked together is, unfortunately, a real life scenario.
And of those area's that we cannot look inside, such as car or avionic software, we all think it is 100% properly designed and tested. But recent issues with certain Prius cars say otherwise. Especially of their vulnerability to be hacked.

Engineers tend to stick to what they know, and what they like*.
Especially the latter one is a serious obstacle in innovation of engineering methods.

Sticking to legacy stuff (methods/languages from the previous era) is not something what he likes much. He's right, but please read at the *.
About legacy stuff, that is what took down Apple with the Thunderstrike exploit. Go watch that, also interesting.
 

Online Howardlong

  • Super Contributor
  • ***
  • Posts: 5313
  • Country: gb
Re: while loop in software
« Reply #241 on: January 05, 2015, 11:03:49 am »
I mentioned this already; it was summarily ignored.

Not sure it was necessarily ignored, wasn't there concern that having a literal on the left and the lvalue to the right made the code less readable in that the brain just doesn't naturally work in the way that's being recommended.

Personally I'm a bit too long in the tooth to change my own way of doing things, and I'm quite capable of determining the difference between == and = , although the danger really comes when frequently switching between languages or when the programmer is a young player in C/C++. But even then, these days the compiler will spout a warning. We all pay attention to those don't we?

My preference to to have code that generates zero warnings, and that's not achieved by relaxing the warning level. I'd have thought that's a good start for anyone. The only problem is that different compilers and different versions of compilers (and header files) frequently change the emission of warning messages, so something that compiles perfectly well one day might not the next if the compiler's updated.

Regarding the video, I guess I'm a bit thick but I didn't know anything more at the end of it than at the start, partly because what was being described was no surprise, and partly because some of the nomenclature and acronyms assumed prior knowledge and were not explained, so another hour of my life gone I guess!

(My own hobbyhorse is the plethora of non-deterministic, often but not always distributed systems, and how difficult they are to test and analyse properly, both functionally but particularly non-functionally).
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #242 on: January 05, 2015, 11:22:37 pm »
Quote
if you ever get a real job with a large corp, you might be surprised to find there are strict standards
And if you get two real jobs with two large corporations, you might be surprised to find how different and mutually contradictory they are...
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #243 on: January 06, 2015, 01:47:01 am »
Depends on the language, I would say in my C-hating way.  I've worked in a couple Java positions, both had nearly identical style and structure guidelines.  One place allowed no more than 30 lines of code per method, the other 35, that was the only difference.  (This would be a bizarre metric for someone who is used to purely procedural languages like C.)
 

Offline Helix70

  • Supporter
  • ****
  • Posts: 289
  • Country: au
  • VK4JNA
Re: while loop in software
« Reply #244 on: January 06, 2015, 01:59:47 am »
Depends on the language, I would say in my C-hating way.  I've worked in a couple Java positions, both had nearly identical style and structure guidelines.  One place allowed no more than 30 lines of code per method, the other 35, that was the only difference.  (This would be a bizarre metric for someone who is used to purely procedural languages like C.)
Its a bizarre metric when you are speed and resource constrained, as the processor cycle and stack overheads for function calling can cause issues. Horses for courses, there is no real correct answer IMO.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #245 on: January 06, 2015, 02:44:25 am »
A good C/C++ compiler inlines short functions anyway so there is no need to do the compiler's work.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #246 on: January 06, 2015, 04:30:00 am »
Depends on the language, I would say in my C-hating way.  I've worked in a couple Java positions, both had nearly identical style and structure guidelines.  One place allowed no more than 30 lines of code per method, the other 35, that was the only difference.  (This would be a bizarre metric for someone who is used to purely procedural languages like C.)
Its a bizarre metric when you are speed and resource constrained, as the processor cycle and stack overheads for function calling can cause issues. Horses for courses, there is no real correct answer IMO.
True, but we had (at both places) plenty of hardware to throw at those issues.

Other situations would require other rules, certainly.

There is no one answer for all, but there can be one right answer in a given situation.
 

Offline Rigby

  • Super Contributor
  • ***
  • Posts: 1476
  • Country: us
  • Learning, very new at this. Righteous Asshole, too
Re: while loop in software
« Reply #247 on: January 06, 2015, 04:33:30 am »
A good C/C++ compiler inlines short functions anyway so there is no need to do the compiler's work.
A good C compiler will do much for you, they have come a looong way, certainly.

Since C isn't type safe nor memory safe (and languages have existed since the early 1970s which are) I will cling hopelessly to my distaste for the language.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #248 on: January 06, 2015, 04:48:12 am »
True, but we had (at both places) plenty of hardware to throw at those issues.

Other situations would require other rules, certainly.

There is no one answer for all, but there can be one right answer in a given situation.

True, and the answer for an OS for > 99.99% of current systems is C & C++ without those, there are no computers.

for 99.99% of that left over 0.01% like old DEC systems, but those where probably written in VAX Assembly. Old Micros well, was assembly as well. Sure they did run basic interpreters but they were written in assembly.

Edit: that leaves 0.0001% for other than C/C++ or assembly and I'm being generous because it's probably lower than 10^-12

Other compilers will rely on libraries that are most likely C or C++ so I'm not sure about the dislike.

But I agree with one thing, over 90% of the code out there is not fully tested and I'm being generous. Well... it has been tested... by the end users, but it doesn't mean any regression or code changes resulted on that testing.

So if you really distaste C or C++, turn off your system, like it or not there is no replacement yet.

« Last Edit: January 06, 2015, 04:49:55 am by miguelvp »
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #249 on: January 06, 2015, 06:44:23 am »
A good C compiler will do much for you, they have come a looong way, certainly.

Since C isn't type safe nor memory safe (and languages have existed since the early 1970s which are) I will cling hopelessly to my distaste for the language.

Have you tried go?  https://golang.org/

It's suppose to be more system oriented than Java and more productive than C/C++.

I am still waiting for the right project to give it a try.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #250 on: January 06, 2015, 07:02:41 am »
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6189
  • Country: us
Re: while loop in software
« Reply #251 on: January 06, 2015, 07:34:51 am »
well...

https://go.googlesource.com/go/+/go1.4/src/lib9/

It is built on solid foundations ;-) 

Have you played with it? It's supposed to solve the deployment hassle of Java. AFAIK no portable GUI library yet so this is a drawback.

 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: while loop in software
« Reply #252 on: January 06, 2015, 07:40:12 am »
Only plan9 I've looked at was rudp (as in reliable udp) did not use it, just curiosity and didn't look too good, but this was a while back so I don't recall what I didn't like.

Funny thing I didn't see an rudp.c in that directory ;)

Edit: but to answer your question, I didn't use go and didn't collect $200 :)
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4192
  • Country: us
Re: while loop in software
« Reply #253 on: January 06, 2015, 08:04:59 am »
Didn't Apple write their system software in a Pascal variant, back in the 68000 days?
I suppose that somewhere there is an interesting story about what happened to cause them to change their minds. (has it been made public, that anyone knows?)
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26682
  • Country: nl
    • NCT Developments
Re: while loop in software
« Reply #254 on: January 06, 2015, 01:43:53 pm »
A good C/C++ compiler inlines short functions anyway so there is no need to do the compiler's work.
A good C compiler will do much for you, they have come a looong way, certainly.

Since C isn't type safe nor memory safe (and languages have existed since the early 1970s which are) I will cling hopelessly to my distaste for the language.
I hear you  ;) I hope to continue my adventure with Lua on an ARM microcontroller in the near future!
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline paf

  • Regular Contributor
  • *
  • Posts: 91
Re: while loop in software
« Reply #255 on: January 15, 2015, 09:43:29 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.

Hmm, actually, this has a place in defensive programming, but for the test of equality.

Consider

if (x == 1)

A common typo is

if (x = 1)

which compiles without warning (on most compilers I use anyway). This code does something totally different and usually is undesired.

If you change this to:

if (1 == x)

instead, the typo

if (1 = x)

declares an error, as you cannot assign x to a constant. So once you get into this habit,

if (0 < x)

is a natural extension, and good practice to reducing coding errors.

No, no, no.

Any decent C compiler will warn you that  you have an assignment used as a truth value if you write things like if (x = 1).

GCC and Clang ail warn you, and that covers ARM, AVR, MIPS (PiC32), MSP430 and others.


If you are programming in C:

Turn on all the compiler warnings.

Pass your code through splint    [url=http://www.splint.org/]http://www.splint.org/[/url]

If possible check it with Valgrind    [url=http://valgrind.org/]http://valgrind.org/[/url]

Thanks

 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf