Is it important to know about GOTOs?

  • (10 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5
  • Last »

143 Replies - 6548 Views - Last Post: 13 October 2012 - 01:05 PM

#31 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,594
  • Joined: 16-October 07

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 09:34 AM

View PostG0rman, on 11 October 2012 - 11:03 AM, said:

There are no modern languages where you "must" use for loops.


But loops aren't evil. :P

All imperative languages I can think of "must" use loops. Please enlighten me otherwise.


View PostG0rman, on 11 October 2012 - 11:03 AM, said:

Feel free to comment on the examples.


The examples that use break? Again, as stated before, break is NOT GOTO. It doesn't just jump to some arbitrary point. It does exit it's current control structure in a consistent manner.

View PostG0rman, on 11 October 2012 - 11:03 AM, said:

It seems like you are just saying "but they are really bad" instead of giving reason.


Hardly. That you even need a reason explicitly stated means the chasm of understanding is probably too great. Simply, a GOTO allows code execution to move to an arbitrary point. This type of behavior is unnecessary in procedural languages. If it's unclear why being able simply relocate execution in an inconsistent fashion is problematic, then we're probably done.


View PostG0rman, on 11 October 2012 - 11:03 AM, said:

Multiple return statements are the fruit of the devil after all!


No, they are flow control statements. They leave a block in a consistent and understood way. While some dislike this, many take no issue with it. Unlike, say, GOTO.

Note, SQL does NOT have a GOTO. SQL is a declarative language with zero flow control. PL/SQL and T-SQL do have a GOTO. I do use the GOTO this context, mostly because of the primitive nature of the languages and the quirks of transactional processing.
Was This Post Helpful? 1
  • +
  • -

#32 wordswords  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 76
  • View blog
  • Posts: 272
  • Joined: 17-December 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 09:37 AM

I have seen GOTO's being used instead of throwing exceptions in languages which don't have exception handling, such as C. But even then, there are ways to do it better, such as returning constant integers from a function call, or passing state objects as pointers which you can change by reference.

I honestly have never found any situation where it is a good idea to use GOTO statements. I think it will prove impossible to argue that anyone should use them.

If you're interested in a detailed explanation as to why gotos are bad, then the original letter by Dijkstra in 1963 (that is nearly 50 years old!) is a good read:

http://dl.acm.org/ci...d=362929.362947

This post has been edited by wordswords: 11 October 2012 - 09:38 AM

Was This Post Helpful? 0
  • +
  • -

#33 G0rman  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 46
  • Joined: 16-October 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 09:42 AM

View Postbaavgai, on 12 October 2012 - 12:34 AM, said:

All imperative languages I can think of "must" use loops. Please enlighten me otherwise.

Sure, give me a piece of code and I'll rewrite it without loops.


View Postbaavgai, on 12 October 2012 - 12:34 AM, said:

The examples that use break? Again, as stated before, break is NOT GOTO. It doesn't just jump to some arbitrary point. It does exit it's current control structure in a consistent manner.

In what way is goto inconsistent? Break does jump to an arbitrary point (see:java)

View Postbaavgai, on 12 October 2012 - 12:34 AM, said:

Hardly. That you even need a reason explicitly stated means the chasm of understanding is probably too great. Simply, a GOTO allows code execution to move to an arbitrary point. This type of behavior is unnecessary in procedural languages. If it's unclear why being able simply relocate execution in an inconsistent fashion is problematic, then we're probably done.

You keep throwing around "inconsistent". Are you referring to the handling of the dynamic links? I read a lot about how goto is implemented, and it seems fairly well handled to me. I don't think a blanket statement of "any use of goto is bad" is justified.

I have heard 0 legitimate reasons as to why jumping within a block/clause/scope.

View Postbaavgai, on 12 October 2012 - 12:34 AM, said:

No, they are flow control statements. They leave a block in a consistent and understood way. While some dislike this, many take no issue with it. Unlike, say, GOTO.

> No, they are flow control statements.
http://en.wikipedia....ki/Control_flow
Case closed? :P

I'm joking, I know what you mean. Conditionals and loops are structured programming elements, goto is a mere primitive.
I don't see what is inconsistent or mysterious about gotos.

View Postwordswords, on 12 October 2012 - 12:37 AM, said:


Not sure if I have read that particular letter, but I have read his papers on the matter.

I found the logic of "conditionals and loops are the only possible control structures in existence" to be a bit sketchy. But the stuff on tail calls was enlightening - I had a feeling that compilers would have optimized that kind of thing, but never tried it myself (how hard is it to compile some code ey? Better wait for someone else to do it... such lazyness)

EDIT: Actually the letter you linked basically just covers "it is hard to follow" - which is very subjective.
As much as I hate to disagree with Knuth, bad programming is confusing, not language primitives.

This post has been edited by G0rman: 11 October 2012 - 09:55 AM

Was This Post Helpful? 0
  • +
  • -

#34 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,696
  • Joined: 19-March 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 10:05 AM

View PostG0rman, on 11 October 2012 - 11:21 AM, said:

Well it [Java's break] is a named break, and seeing as the main "accepted use of gotos" is what Java's break is made to do, it is very safe to call it "basically a goto".


Not at all. A goto allows you to go anywhere. Unrestricted jumps. A break is a return to the main flow of control. Completely different thing. If a goto's "main accepted use" is a break, replace the unrestricted jump with a restricted goto.

Quote

It seems like you imply that the role of a language is to "enforce discipline on a programmer". It's not like I go around not indenting in Java because I don't have to. But on the other hand I don't love Python just because it forces me to indent.


A programming language is a set of tools for generating instructions to the machines. A good programming language provides the right set of tools. Precision tools are preferable to blunt instruments, no?

This post has been edited by jon.kiparsky: 11 October 2012 - 10:07 AM

Was This Post Helpful? 0
  • +
  • -

#35 G0rman  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 46
  • Joined: 16-October 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 10:12 AM

View Postjon.kiparsky, on 12 October 2012 - 01:05 AM, said:

Not at all. A goto allows you to go anywhere. Unrestricted jumps. A break is a return to the main flow of control. Completely different thing. If a goto's "main accepted use" is a break, replace the unrestricted jump with a restricted goto.

The thing is, most languages don't have this kind of mechanism
A: while (true) {
    B: while (true) {
         break A;
    }
}

So they can't emulate a goto. Java does, so it does emulate a goto.

And yup, you just reiterated the whole argument against gotos; "we have other things that can do what gotos do" (more on that below)

View Postjon.kiparsky, on 12 October 2012 - 01:05 AM, said:

A programming language is a set of tools for generating instructions to the machines. A good programming language provides the right set of tools. Precision tools are preferable to blunt instruments, no?

I concur.

But it's not like a carpenter shuns the router just because it is dangerous. A carpenter accepts that it is dangerous, and acknowledges it's power. There's a myriad of tools that each could replace part of the functionality of a router. Yet the router's power and flexibility means it wins out.

In programming it is the opposite situation, we want the most restricted and least powerful solution. A goto can emulate loops and conditional blocks, as well as functions and subroutines. Yet we don't want to use it precisely because we have more restricted solutions.

If we look at Knuth and other critiques, we can say two things about acceptable use of goto;
1) So long as it is easy to understand
2) So long as it is easy to read
Was This Post Helpful? 0
  • +
  • -

#36 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,696
  • Joined: 19-March 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 10:26 AM

It's starting to sound to me like you're looking for validation on this. You're not getting it from me. There are reasons to use lower-level languages, and when you do, you might want to use a goto. Most of us prefer to work in higher-level languages with modern control flow, and that doesn't include goto.

I also prefer not to do my own memory management and I like to have String classes and pre-existing data types like lists and maps. So sue me. I'm too busy to reinvent those wheels, and trying to reinvent for loops and returns and breaks seems similarly frustrating.

The underlying problem here is - why do you want a goto to begin with? That's starting to look like a danger sign. In java, if your structure feels like it requires a cast you usually look at that as a sign you need to reconsider your assumptions. The same seems to hold with a goto: the fact that you want it means you're doing something wrong, I'd say.


Quote

So they can't emulate a goto. Java does, so it does emulate a goto.


No.

This post has been edited by jon.kiparsky: 11 October 2012 - 10:27 AM

Was This Post Helpful? 0
  • +
  • -

#37 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,594
  • Joined: 16-October 07

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 11:02 AM

View PostG0rman, on 11 October 2012 - 12:42 PM, said:

Sure, give me a piece of code and I'll rewrite it without loops.


Using gotos, no doubt. No thanks. "Imagine there's no GOTOs. It's easy if you try..."

The point of a loop is that it defines scope. Yes, it's really just a fancy goto under the covers, but that's not the point. The point is that programming structures with well defined behaviors make programs more manageable.


View PostG0rman, on 11 October 2012 - 12:42 PM, said:

You keep throwing around "inconsistent".


It's about destination.

All the programming structures that have jump well wrapped define very precisely where the execution pointer will wind up. A goto just sends that pointer to a label somewhere. Up or down, in or out of at a block, there's no way to tell. This is arbitrary and inconsistent.

Java's break is... unfortunate. When used as a break like in C, it's acceptable. However, you are correct, the labeled break is very gotoesque and should be avoided as well. Doubtless some Java programmer with the fondness for goto you have slipped that bit of nastiness in.

Look, you want to use goto, have at. Clearly you have an attachment to them. I'm afraid you'll have a hard time finding fellow goto enthusiasts this century.

Even if GOTOs aren't "evil" they are still very, very far away from being considered a good practice. Why should such a thing be offered to new students? As an option? To perpetuate a mode of thought that was recognized as counter productive before they were born? Why?!?
Was This Post Helpful? 1
  • +
  • -

#38 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4433
  • View blog
  • Posts: 7,702
  • Joined: 08-June 10

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 11:44 AM

View PostG0rman, on 11 October 2012 - 11:33 AM, said:

View PostCurtis Rutland, on 12 October 2012 - 12:25 AM, said:

Misleading. For instance, goto is a keyword in Java, but is not actually implemented. ASP.NET isn't a language, so I don't even know why you included it there. It uses VB.NET or C# as its guts. SQL? That's a very different paradigm, and it's also not what I'd call a modern language. Assembly? Well, no shit. But it's neither high level or modern.

So in other words
"No one should learn GOTO because it isn't used in some modern languages and in particular paradigms and because it is evil"?


Nope. You're putting words in my mouth. You were the one that suggested that all these languages have gotos, I'm just throwing out why that doesn't make sense. You have no choice when you're using assembly, but in any higher level language that's structured and procedural, you've got better choices.

On the other hand, you've had programmers explaining why goto is bad for almost fifty years. Read the whitepapers if you really care. We're not making this stuff up.

View PostG0rman, on 11 October 2012 - 11:33 AM, said:

View PostCurtis Rutland, on 12 October 2012 - 12:25 AM, said:

That's a bullshit example, because you could completely replace your gotos with subs/methods without any difficulty or confusion at all.

Of course. I said that didn't I? It's hard to think of an example on the spot.


That's kinda my point. You can't come up with a good example where functions/methods and other proper control statements aren't just as good or better off hand, because there really aren't very many. And as Jon says, if you find yourself in a situation where goto is the best approach, that means you've already done something wrong and should be refactoring so you don't have to do that in the first place.

I'm with the others here; you're looking for someone to validate your opinion. We're not going to do it. Gotos have very little place in modern, structured programming. If you're still going to use them, fine, but let's not advocate poisoning the next generation of programmers by teaching goto. If they want to learn about it, they can look it up. Also, if you're still going to use them, I hope you enjoy solo projects, because nobody is going to want to work with your code.
Was This Post Helpful? 0
  • +
  • -

#39 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:08 PM

View PostCurtis Rutland, on 11 October 2012 - 07:44 PM, said:

I'm with the others here; you're looking for someone to validate your opinion.
We're not going to do it.

We? You arrogant self important nobody. You ain't speaking for me. I'm in agreement with them.

Quote

Gotos have very little place in modern, structured programming. If you're still going to use them, fine, but let's not advocate poisoning the next generation of programmers by teaching goto.

Not even as historically or like the approach I'm advocating, which considers the "modern" structured programming constructs as an abstraction over If and GoTo. In Nemerle:- The If statement is a Macro over the core Pattern Matching construct. Even the For-Loop is a Macro.

Quote

If they want to learn about it, they can look it up. Also, if you're still going to use them, I hope you enjoy solo projects, because nobody is going to want to work with your code.

Structured Programming also isn't Immune to creating and huge pile steaming of shit code.
It too easy to just jump in code and a be swim around in a cesspit of crap.

Thinking and Analysis of the Design before typing a single character in the IDE, is the best approach to take prevent that happening. Jumping in to a swimming pool of water.

This post has been edited by AdamSpeight2008: 11 October 2012 - 12:14 PM

Was This Post Helpful? 0
  • +
  • -

#40 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1940
  • View blog
  • Posts: 4,027
  • Joined: 11-December 07

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:09 PM

I wrote some tasty gotos today, in a class called meatballs.

I used to like goto on the Spectrum because you could do stuff like in line 20:

10 INPUT a
20 GOTO a * 100
30 GOTO 10
100 PRINT "You chose 1"
110 GOTO 10
200 PRINT "You chose 2"
210 GOTO 10
9998 PRINT "Invalid choice"
9999 GOTO 10


These days I use a map and the strategy pattern. I guess a*100 is a hash function of sorts.
Was This Post Helpful? 1
  • +
  • -

#41 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4433
  • View blog
  • Posts: 7,702
  • Joined: 08-June 10

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:21 PM

Quote

Not even as historically or like the approach I'm advocating, which considers the "modern" structured programming constructs as an abstraction over If and GoTo


I suppose that would depend on what we're talking about here. In school, yeah, it would probably be worth discussing how you used to have to do things. It would be especially useful to explain to more advanced classes how modern control structures are abstractions over the more primitive instructions, because it's always good to actually know what your code does.

It just sounds like he's advocating just teaching what goto does and letting students make of it what they will.

Quote

Structured Programming also isn't Immune to creating and huge pile steaming of shit code.
It too easy to just jump in code and a be swim around in a cesspit of crap.


No doubt, but as baavgai said earlier, modern constructs make it easier to make better code. Goto makes it harder. Just because either can give you crap doesn't make them equal.

Quote

Thinking and Analysis of the Design before typing a single character in the IDE, is the best approach to take prevent that happening. Jumping in to a swimming pool of water.


I couldn't agree more.
Was This Post Helpful? 1
  • +
  • -

#42 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,696
  • Joined: 19-March 11

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:24 PM

View PostAdamSpeight2008, on 11 October 2012 - 02:08 PM, said:

Structured Programming also isn't Immune to creating and huge pile steaming of shit code.
It too easy to just jump in code and a be swim around in a cesspit of crap.



Nobody claimed it was. The issue is not how to devise a language which cannot express errors, the issue is ridding languages of constructs which encourage error and replacing them with ones which are more expressive of the things we actually want.
Was This Post Helpful? 0
  • +
  • -

#43 BBeck  Icon User is online

  • Here to help.
  • member icon


Reputation: 560
  • View blog
  • Posts: 1,262
  • Joined: 24-April 12

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:40 PM

View Postbaavgai, on 11 October 2012 - 08:57 AM, said:

For Jack's example:
bool hasK(int k) {
	for(int i=0; i<10; i++) {
		for(int j=0; j<10; j++) {
			if (i * j == k) { return true; }
		}
	}
	return false;
}

int k=49;
if (!hasK(k)) { printf(“didn’t find %d!”,k); }





There's one part of me that says "You know better than to get into this. Discussing the 'best' way to code with programmers is like talking about the correct religion or the who's 'right' in politics." Then there's the other side of me that has just can't resist.

So, before I get into tearing baavgai's code apart, let me start by saying I've seen a lot of his posts here and I have a tremendous amount of respect for him. He's probably a better programmer than I am. Also, I would add that the code above is elegant and looks highly professional to me. So here go's... :-)

jumping to different point...
First of all, if I had someone who worked for me write a "goto" type branch to a label in anything other than assembler, I would at least consider firing them on the spot. I can't think of any instance where I think it would be a good idea, and that includes the use of break to break out of the middle of a loop.

I definately think 100% of the language should be taught, including spaghetti code branching like "goto". But it should be taught as to why it's "wrong". Just because a language allows you to do something doesn't mean you should.
jumping back (probably to prove that jumping randomly all over the place is confusing. ;-)

I'm also a bit "religious" about having more than one return point from a procedure, function, or method. And that's why I'm using the above code as an example. Maybe the example above is not the best example to pick apart, because it shows an appreciation for code optimization, and so this particular example "may" actually be the best way possible to write this code. That being said, it's always a balance between understandability of the code and performance.

This is kind of a bad example, because this code is going to perform very well, and that often justifies it's "lack of readability". Furthermore, it's so short and sweet that it's almost a waste of time to make it even more "self documenting". This is probably more of an issue when you have a function that has substantially more code than 3 or 4 lines. But this is the example given, so it's what I'll work with. ;-)

So, here's how I might re-write that code (Keep in mind that some of this really just boils down to opinion):
bool IsInRangePrime(int NumberBeingTested) 
{
  int FirstMultiplier = 0;
  int SecondMultiplier = 0;
  bool FoundNonPrime = false;


  while ((FirstMultiplier<10 && !FoundNonPrime))
  {
    while ((SecondMultiplier<10 && !FoundNonPrime))
    {	
      if (FirstMultiplier * SecondMultiplier == NumberBeingTested) 
	  {
		  FoundNonPrime = true;
	  }
      SecondMultiplier++;
    }
    FirstMultiplier++;
  }

  return FoundNonPrime;
}




I know the original was given based on previous code given and as a quick example, and not as the 'absolute ultimate' way to write this. But I'll just take it as it is and point out how I 'might' approach the problem.

First of all:
bool hasK(int k)

This is kind of "nit picky", but the first thing I would do is back up a couple of steps and try to understand really what this function does. It's certainly about "Having K", but what does it mean to "have" and - more importantly - why do we care.

I chose to go with this:
bool IsInRangePrime(int NumberBeingTested)

That's because ultimately this function tests for prime numbers above 10 who's factors are less than 10. So, I went with "IsInRangePrime" in order to give more "depth" to explaining what the function is doing. It's "nit picky", I know. I would also include comments and a comment header to explain in detail what this function does if I were really going to do it right (I'm REALLY guilty of not commenting enough and I usually write headers after the fact, if at all - but I'm talking about best practices rather than what I do. ==> Do as I say, not as I do! ;-) )

I also changed k to "NumberBeingTested" to make it more clear what the reason for K being there actually is. (Again, "nit picky" because the code example given was so short and sweet that you can pretty much see what it does and the function was named "we're trying to find K". But I guess my point is, that it's real easy to forget what "k" or "i" is in a large block of code. Then you have to go read code to figure out what it is rather than having it's explanation right there in the variable name.

You'll notice that I've also named 'i' and 'j' to 'try' and give them more descriptive names according to what they do in the code, although you can see that I didn't do much better in the given example. (In fact I would be awefully tempted to give in and use 'i' and 'j' here, but I try and use descriptive names for itterators like this to describe what they are itterating through. But honestly, it may be more trouble than it's worth a lot of times.)

I initialize them, partially for debugging, so that I know what value they started out with. This is a bigger issues in some languages than others. I also gather up all my variables at the top where they can easily be found (often commenting each and every one so that if I have a question of what a variable is doing in the code I just jump to the top of the function and read the comments for that variable.) Especially for a 'for' loop I might break this rule, but I try to get all the variables up top in one place where they're easy to find when you're visually going through the code.

In this case, it takes 3 extra machine language instructions to initialize the 3 variables up top.

I added "FoundNonPrime" as a loop exit condition and return value. That's actually one of the most expensive changes here, because it's something not in the original example. It's also tested in every loop, which is about one extra assembly language instruction per iteration of each loop. That's not much, but it "could" add up.

But anyway, it makes it pretty clear that the function will exit immediately when the number is determined to be non-prime (with the assumption being that it is prime if it not-not-prime). Notice that we've got way too many double negatives going on here, which should be resolved (if possible).

I changed to "while" statements because they avoid multiple exit points. They compile differently than "for" loops, but it's pretty close to the same machine code when it's compiled. The "&& !FoundNonPrime" is an extra test as mentioned before. It's testing whether it's time to exit the loop or not.

One thing you will notice is that I've moved all the open braces to their own starting line. This has been seriously bothering me for a long time in other people's code, because I see the opening braces with their statement in most of the code I read from other people. I knew it bothered me, but I just recently figured out why.

The reason I prefer this:
for(int i=0; i<10; i++) 
{
  for(int j=0; j<10; j++) 
  {
    if (i * j == k) 
    { 
      return true; 
    } 
  }
}



over the original is that it's much more clear at a glance. This is a terrible example, because the original code was short and sweet and practically one line of code. But looking this as a "general programming best practice" rather than for this specific code:

Having the braces on their own line makes it easier to match them up visually. But the most important thing is that when I see two lines of code next to one another but indented, I think "that's one line of code that got word wrapped".

Compare:
for(int i=0; i<10; i++){
  for(int j=0; j<10; j++){

To this:
for(int i=0;
 i<10;
 i++){

To this:
for(int i=0; i<10; i++)
{
  for(int j=0; j<10; j++)
  {



Not the best example here, but my point is that one has the lines "word wrapped" because of limitations of getting a "long" line on the screen at once and the other is together just "because". When I see two statements touching together like that, indented, and without a brace seperating them, my mind interprets that as a single line that's been "word wrapped". That's why I've decided to take a hard stance against it. It increases the vertical length of the code, but my opinion is that it makes the code easier to read at a glance, rather than requiring thought to interpret what the code means.

Anyway, I think the example I gave is considerably easier to read and much more "self documenting" (if you ignore the fact that the original was about one line of code - it would have made a better example if the function where a lot longer).

No doubt the original will perform better. And for that reason, "it's more elegant". I myself might write it the original way, if I thought the over-all program would perform better because of it.

But often, I'm writing in C# or some language that isn't as optimized as C++ is, in the first place. And even here, I would be inclined to favor readability and "self documenting" over performance while writing the program. Then if the program did not perform up to expectations, I would go back and look for sections of code that get called millions of times and look at ways to optimize the code, such as the original example.

For performance comparisons, I disassembled them. ;-)

bool hasK(int k) 
{
00E013A0  push        ebp  
00E013A1  mov         ebp,esp  
00E013A3  sub         esp,0D8h  
00E013A9  push        ebx  
00E013AA  push        esi  
00E013AB  push        edi  
00E013AC  lea         edi,[ebp-0D8h]  
00E013B2  mov         ecx,36h  
00E013B7  mov         eax,0CCCCCCCCh  
00E013BC  rep stos    dword ptr es:[edi]  
	for(int i=0; i<10; i++) 
00E013BE  mov         dword ptr [i],0  
00E013C5  jmp         hasK+30h (0E013D0h)  
00E013C7  mov         eax,dword ptr [i]  
00E013CA  add         eax,1  
00E013CD  mov         dword ptr [i],eax  
00E013D0  cmp         dword ptr [i],0Ah  
00E013D4  jge         hasK+62h (0E01402h)  
	{
	for(int j=0; j<10; j++) 
00E013D6  mov         dword ptr [j],0  
00E013DD  jmp         hasK+48h (0E013E8h)  
00E013DF  mov         eax,dword ptr [j]  
00E013E2  add         eax,1  
00E013E5  mov         dword ptr [j],eax  
00E013E8  cmp         dword ptr [j],0Ah  
00E013EC  jge         hasK+60h (0E01400h)  
	{
		if (i * j == k) 
00E013EE  mov         eax,dword ptr [i]  
00E013F1  imul        eax,dword ptr [j]  
00E013F5  cmp         eax,dword ptr [k]  
00E013F8  jne         hasK+5Eh (0E013FEh)  
		{ 
			return true; 
00E013FA  mov         al,1  
00E013FC  jmp         hasK+64h (0E01404h)  
		} 
	}
00E013FE  jmp         hasK+3Fh (0E013DFh)  
	}
00E01400  jmp         hasK+27h (0E013C7h)  
	return false;
00E01402  xor         al,al  
}


33 lines of machine code






bool IsInRangePrime(int NumberBeingTested) 
{
00221430  push        ebp  
00221431  mov         ebp,esp  
00221433  sub         esp,0E4h  
00221439  push        ebx  
0022143A  push        esi  
0022143B  push        edi  
0022143C  lea         edi,[ebp-0E4h]  
00221442  mov         ecx,39h  
00221447  mov         eax,0CCCCCCCCh  
0022144C  rep stos    dword ptr es:[edi]  
  int FirstMultiplier = 0;
0022144E  mov         dword ptr [FirstMultiplier],0  
  int SecondMultiplier = 0;
00221455  mov         dword ptr [SecondMultiplier],0  
  bool FoundNonPrime = false;
0022145C  mov         byte ptr [FoundNonPrime],0  


  while ((FirstMultiplier<10 && !FoundNonPrime))
00221460  cmp         dword ptr [FirstMultiplier],0Ah  
00221464  jge         IsInRangePrime+72h (2214A2h)  
00221466  movzx       eax,byte ptr [FoundNonPrime]  
0022146A  test        eax,eax  
0022146C  jne         IsInRangePrime+72h (2214A2h)  
  {
    while ((SecondMultiplier<10 && !FoundNonPrime))
0022146E  cmp         dword ptr [SecondMultiplier],0Ah  
00221472  jge         IsInRangePrime+67h (221497h)  
00221474  movzx       eax,byte ptr [FoundNonPrime]  
00221478  test        eax,eax  
0022147A  jne         IsInRangePrime+67h (221497h)  
    {	
      if (FirstMultiplier * SecondMultiplier == NumberBeingTested) 
0022147C  mov         eax,dword ptr [FirstMultiplier]  
0022147F  imul        eax,dword ptr [SecondMultiplier]  
00221483  cmp         eax,dword ptr [NumberBeingTested]  
00221486  jne         IsInRangePrime+5Ch (22148Ch)  
	  {
		  FoundNonPrime = true;
00221488  mov         byte ptr [FoundNonPrime],1  
	  }
      SecondMultiplier++;
0022148C  mov         eax,dword ptr [SecondMultiplier]  
0022148F  add         eax,1  
00221492  mov         dword ptr [SecondMultiplier],eax  
    }
00221495  jmp         IsInRangePrime+3Eh (22146Eh)  
    FirstMultiplier++;
00221497  mov         eax,dword ptr [FirstMultiplier]  
0022149A  add         eax,1  
0022149D  mov         dword ptr [FirstMultiplier],eax  
  }
002214A0  jmp         IsInRangePrime+30h (221460h)  

  return FoundNonPrime;
002214A2  mov         al,byte ptr [FoundNonPrime]  
}

37 lines of machine code



The original compiled into 33 lines of machine code. Mine compiled into 37 lines of machine code. Keep in mind that this isn't a 1 to 1 comparison because some of the instructions are different and every instruction has a different time cost (cpu cycles to execute). But just looking at the number of instructions, it was a difference of 4 instructions.

3 of those instructions are outside of both loops and only called once at the beginning of the function. So, they are relativelly low cost. That leaves basically one instruction inside the loops ( I think it's the exit loop test) that is more than what was in the original. It's inside the loops, so it gets multiplied by the number of times looped (which will be greater the larger the k value is to a maximum of 81 extra instructions).

We're talking microseconds of difference for something that "theoretically" is much more "self documenting" and readable.

On the other hand, in game programming, every microsecond "can" count. So ultimately, it comes down to a trade off between readability and performance.

And in the example given, it annoys me because it has multiple exit points, but if it gets called enough to make that 1 extra machine language instruction increase the frames per second from a visible 26 fps to a (presumably) invisable 32 fps, then you have to appreciate it's short and sweet eleagance.

This post has been edited by BBeck: 11 October 2012 - 01:03 PM

Was This Post Helpful? 3
  • +
  • -

#44 mojo666  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 352
  • View blog
  • Posts: 770
  • Joined: 27-June 09

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 12:57 PM

I'm not familiar with this kind of break in Java, but I am assuming it is not possible to do the following.
A: for()
{
	B: for()
	{
		break: C
	}
}
/*Lots of Code*/
C: //end up here



This is possible with GoTo, and that is the main objection.

The problem with GOTO is that the programmer has the freedom to do nasty things that control structures do not allow. Which "process2" would you rather debug?

/**GOTO Example**/
int x;
int y;

PROCESS1:
	GOTO SOMEWHERE_ELSE
PROCESS2:
	/*code*/
PROCESS3:
	/*code*/
/****************/

/**Control Structure Example**/
int x;
int y;

PROCESS1(x);
PROCESS2(y);
PROCESS3();
/*****************************/



In the GOTO example, we need to see if process2 will even be executed as well as check if any of the variables it uses are altered and this could take an extremely long time. In the control structure example, we know process2 will be executed and it only needs y which was not touched at all. Things like scope and well defined control line transfer are features of control structures that restrict programmers. What does it restrict? Overwriting variables and control transfer. These are things you want to restrict. Since GOTO lacks these restrictions, it means dealing with these programming mistakes is unavoidable. You can claim that it is possible to program just as well with GOTO as control structures, but then why not just use control structures to guarentee the better practices in the first place?

You also need to account for how terrible code comes about in the first place. Rarely does it begin as bad code. More often, it is a simple piece of code that undergoes an evolution as requirements and developers change. What is the developer more likely to do: realise the goto is no longer the proper tool for the new requirement and redesign from the ground up, or just add another noodle to the spaghetti bowl? It is better to make your code correct from the begining and that includes making it hard to screw up. Structures that restrict the programmer make it harder for the programmer to mess up.
Was This Post Helpful? 2
  • +
  • -

#45 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Is it important to know about GOTOs?

Posted 11 October 2012 - 01:02 PM

View PostG0rman, on 11 October 2012 - 05:33 PM, said:

Aren't you glad we have clumsy "conventional" error handling instead of DIY?

It also important to consider the historical context the code was written in.
vb6 didn't have try...catch...throw

When compilers were incredibly basic not like the complex beast of today.
Or where restricted due to space or time constraints.

This post has been edited by AdamSpeight2008: 11 October 2012 - 01:09 PM

Was This Post Helpful? 0
  • +
  • -

  • (10 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5
  • Last »