Slashdot Mirror


Dirty Coding Tricks To Make a Deadline

Gamasutra is running an article with a collection of anecdotes from game developers who had to employ some quick and dirty fixes to get their products to ship on time. Here's a brief excerpt: "Back at [company X] — I think it was near the end of [the project] — we had an object in one of the levels that needed to be hidden. We didn't want to re-export the level and we did not use checksum names. So right smack in the middle of the engine code we had something like the following. The game shipped with this in: if( level == 10 && object == 56 ) {HideObject();} Maybe a year later, an artist using our engine came to us very frustrated about why an object in their level was not showing up after exporting to what resolved to level 10. I wonder why?" Have you ever needed to insert terrible code to make something work at the last minute?

683 comments

  1. Here's one... by Quartz25 · · Score: 5, Funny

    Right before I left from Microsoft: int security = *NULL; // eat it!

    --
    Most people don't get why the integral of "e to the x" is so funny. Most math majors don't have a sense of humor.
    1. Re:Here's one... by Niris · · Score: 2, Interesting

      Oh how I wish I had modpoints. That gave me a good laugh before bed :D +1 point for you, good sir.

    2. Re:Here's one... by pinkushun · · Score: 5, Funny

      Were you also responsible for #DEFINE RND_BSOD = 1 ?

    3. Re:Here's one... by Anonymous Coward · · Score: 0

      We had a nifty Shockwave 3D engine from yonks ago that we dug out for a project. Between flash-based interactive sections were 3D world activities. By the end of the project there were so many activities it came to about 100Mb zipped, and such a poor engine that memory leaks were abundant and while it ran fine for about 4 activities, by the end it crawled like a legless blind drunk puppy.
      So two weekds before deadline, the 3D sections were replaced with pre-rendedered animations and I had to write a sequential loader in flash and hope the client didn't notice.
      Got the file size down to 30Mb, and leaks/crashes were non-existant.
      Why were we working in Flash/Shockwave? The client wanted it to run embedded in a website.

    4. Re:Here's one... by Anonymous Coward · · Score: 0, Troll

      Oh how I wish I had modpoints. That gave me a good laugh before bed :D +1 point for you, good sir.

      Seriously? In English that wouldn't be so funny. It'd be roughly: security is non-existent. So just because it's written in C / C++, it's suddenly a joke? Give me a break.

    5. Re:Here's one... by bytesex · · Score: 1

      Eh no. It would be that the resulting process of the executable, the source code of which contained this line, would be non-existent. As it would crash, as soon as it was encountered.

      --
      Religion is what happens when nature strikes and groupthink goes wrong.
    6. Re:Here's one... by ObsessiveMathsFreak · · Score: 2, Funny

      Don't be absurd. Even the lowliest coder would know enough to write #DEFINE PSEUDO_RND_BSOD = 1

      --
      May the Maths Be with you!
    7. Re:Here's one... by Anonymous Coward · · Score: 0

      Were you also responsible for #DEFINE RND_BSOD = 1 ?

      #DEFINE PSEUDO_RND_BSOD = 1

      There, fixed it.

    8. Re:Here's one... by Anonymous Coward · · Score: 0

      Re: your sig
      Reading Package lists... Done
      Building Dependency Tree
      Reading State Information... Done
      E: Couldn't find Package

    9. Re:Here's one... by Anonymous Coward · · Score: 0

      you didnt rtfa of course... the article was asking for code

    10. Re:Here's one... by foo1752 · · Score: 1

      Don't be absurd. Even the lowliest code would know that it is "#define" and not "#DEFINE" and that there is NO equals sign! Gah!

    11. Re:Here's one... by StikyPad · · Score: 1

      Most people don't get why the integral of "e to the x" is so funny.

      Ohh, nice one! Check this out: Type 58008 into your calculator, then hold it upside down. Go ahead, I'll wait... it's fucking hilarious.

    12. Re:Here's one... by Anonymous Coward · · Score: 0

      woah woah woah! an equals sign in a #define?!

    13. Re:Here's one... by FunkyELF · · Score: 1

      What executable? It didn't compile.
      error: void value not ignored as it ought to be

    14. Re:Here's one... by serutan · · Score: 1

      Wish I'd had the guts to leave something like that behind. /former MSIT drone

    15. Re:Here's one... by severoon · · Score: 1

      So...the Gaming Antihero. He intentionally allocates 2MB of memory needlessly at the beginning of the project so that when they're overbudget on memory he can delete it and save the day. But, in the story in TFA, if he'd never have done that in the first place, everything would've happened the same except they would've reached their memory budget without him having to delete an empty memory buffer. In other words: sooner. And if he'd been hit by a bus and replaced in the meantime...

      Then there's the fake deadline guy that bargains for extra time and lies to his team, telling them they have to deliver against the original, totally unrealistic deadline. So they're taking all sorts of shortcuts to make the deadline (as those described in the article) and working like slaves so they can deliver ahead of schedule...making compromises they don't need to make. Brilliant.

      These people are stupid. How about making honest estimates and doing business correctly?

      --
      but have you considered the following argument: shut up.
    16. Re:Here's one... by Anonymous Coward · · Score: 0

      I once had a code for class that shouldn't have been more than 3 pages long, but mine came out to be 22 pages and it still didn't work right but since I already knew the output I typed in:

      System.out.println(correctOutput); /**I know I cheated but I get the basic idea of
      how this works and didn't feel like working with it anymore*/

      on the 16th or so page on the off chance they wouldn't catch it and I made a 50/50 on the assignment.

    17. Re:Here's one... by kelnos · · Score: 1

      Hopefully not, seeing as the "=" there will likely net you a syntax error when you try to use your preprocessor symbol in the program. (Unless you're doing something retarded, anyway.)

      --
      Xfce: Lighter than some, heavier than others. Just right.
  2. One word.. by consonant · · Score: 5, Funny

    GOTO :-) (or is that two..?)

    1. Re:One word.. by wilx · · Score: 5, Informative

      The goto statement is very useful. Your dislike of it is irrational. Do you even know why you do not like it? Often, goto is the best solution to given problem.

    2. Re:One word.. by blackraven14250 · · Score: 1

      So, where's your example?

    3. Re:One word.. by Anonymous Coward · · Score: 1, Insightful

      It's not irrational. Very often goto is solution to a problem you shouldn't have.

      That, of course, does not invalidate your last comment...

    4. Re:One word.. by EvanED · · Score: 2, Insightful

      Error handling in C code is my typical example of that. It mostly avoids the need for lots of if statements to make sure that you clean up all that you need to and nothing more.

      There are other ways to go about it, but in general I'm not convinced they are better.

    5. Re:One word.. by Anonymous Coward · · Score: 3, Informative

      So, where's your example?

      Finite State Machines. They really are quite difficult to implement without goto logic and is exactly what you do when discussing theory.

    6. Re:One word.. by Anonymous Coward · · Score: 0

      My bad, I forgot about giant switches etc via state encodings. But as below says, they make error handling an easier task as well as some oddly structured loops for which try/catch logic doesn't get you all the way

    7. Re:One word.. by fractoid · · Score: 2, Insightful

      Every control structure in C++ is equivalent to either a goto or jnz plus some syntactic sugar.

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    8. Re:One word.. by Toonol · · Score: 1

      I wouldn't say often, but occasionally, and it's a valuable tool. Goto and If are the primitives that all other control structures are derived from, and it's always useful to have those sorts of raw basics at your disposal. Rigidly adhering to a 'no Goto' policy is too dogmatic.

      That said, I hardly ever need to use Goto. I'm prepared when the time comes, though!

    9. Re:One word.. by Derleth · · Score: 5, Insightful

      Breaking out of a deeply-nested loop, as can happen when you’re looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    10. Re:One word.. by Derleth · · Score: 5, Insightful

      I’m a goto-user, but this is a bad reason to use them: If you regard language features as ‘just’ syntactic sugar, why aren’t you programming in raw machine code? That is what everything eventually gets turned into anyway.

      You use gotos when the normal control structures are inadequate somehow. It doesn’t matter what the compiler does; source code is for humans.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    11. Re:One word.. by Darinbob · · Score: 2, Insightful

      I think a lot of programmers are superstitious. They do what they teachers taught, without ever stopping and thinking about why they were taught that. So you see people instinctively avoid goto's, or forbid them outright when they get edit permission on style guidelines. I've seen some horrible stuff that avoids gotos, complicating code and making it difficult to read. They heard "goto considered harmful" and "you should prefer structured programming" and translated that internally into "thou shalt not use a goto". Some people even avoid "break" or "continue" in C because of similarity to a goto.

      Similarly, the "there shall be only one exit from a function" is often used as a tautology by some. Combine that with a prohibition on gotos (that lets you jump to the cleanup) and things get ugly.

      Granted, you can get rid of a lot of gotos with some simple language additions (such as a "finally" clause or automatic destructors), but if these don't exist the goto works just fine.

    12. Re:One word.. by Anonymous Coward · · Score: 0

      Breaking out of a deeply-nested loop, as can happen when you’re looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.

      This hit the nail on the head.

    13. Re:One word.. by beelsebob · · Score: 1

      Huh?

      FSMs are *easy* to implement without any goto. You simply use an array representing the out edges in the graph, and store the state you're in, then all you need is a loop checking which transition to take, and taking it.

    14. Re:One word.. by beelsebob · · Score: 1

      I use return for that. If I have deeply nested arrays, it's because I'm really representing some more complex data structure, so write a lookup function for that data structure, which itterates through to find the element, and returns, not gotos when it finds it. It's close to the same, but the control flow is much more easily recognised.

    15. Re:One word.. by Anonymous Coward · · Score: 0

      call/CC is better!

    16. Re:One word.. by zwei2stein · · Score: 3, Insightful

      Ewww.

      1) decent languages support labeled for/while cycles and apropriate "break label" constructs. It is not so different from using goto but has much better semantic meaning and thus allows neat optimalizations (with, say, paralelization in mind)

      2) if you do this kind of thing, you are MUCH better off separating lookup code to method or function and simply using return statement once you find it without having to break from cycles per se. Cleaner, more structured.

      --
      -- Technology for the sake of technology is as pathetic as eschewing technology because it's technology.
    17. Re:One word.. by msclrhd · · Score: 1

      Or split out the element retrieval into a function that returns either a reference, pointer or iterator to the element, depending on how you are implementing the multi-dimensional array. You still need to check if an element was found, though (so pointer or iterator is better than a reference, otherwise you are looking at using something like a std::pair or tuple and then the interface gets messy again; exceptions are also a possibility, but are too heavyweight for this, especially in high-level physics or 3d geometry where performance is critical).

    18. Re:One word.. by zwei2stein · · Score: 1

      GOTO is weapon of mass code destruction in hands of novice programmer, I'd say that is good enough reason to be vary of its use.

      Alternate structures that 'hide' goto exist for reason: They increase readability of code and add semantics to what is happening. Not to just get rid of eeeevil goto, but get rid of assemblerey 'jump'.

      And frankly, I have yet to see goto use that was not caused by ignorance about some constructs - i.e. break.

      --
      -- Technology for the sake of technology is as pathetic as eschewing technology because it's technology.
    19. Re:One word.. by Derleth · · Score: 1

      I use return for that.

      This is conceptually no different from goto, but I agree that it could be more intuitive for some people.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    20. Re:One word.. by shtrom · · Score: 1

      Every control structure in C++ is equivalent to either a goto or jnz plus some syntactic sugar.

      Yes, but it's this very syntactic sugar which makes the codes structure easier to follow for a human. Once code is compiled, it doesn't matter to the CPU whether it was generated from a spaghetti plate of GOTOs or some nicely ordered conditionnal statements. However, the generated code tends to be better when the source code is put in a way allowing a programmer to more easily follow its logic and correct the potential errors in the execution flow.

    21. Re:One word.. by SlashWombat · · Score: 1

      Agreed ... people who do not like GOTO have no idea what they are talking about. To begin, the underlying compiled machine code is actually full of goto's. Secondly, Kernighan (or was it Ritchie?) Only suggested it was bad, but that it did have its place. (From memory, he also said that that the original C compiler actually had two GOTO's within)

    22. Re:One word.. by Derleth · · Score: 4, Interesting

      decent languages support labeled for/while cycles and apropriate "break label" constructs.

      You often cannot develop software with the language you want, but must develop it with the language you have. C has no such features and, therefore, goto is used more often than in languages that have them. Fit the strategy to the tool.

      if you do this kind of thing, you are MUCH better off separating lookup code to method or function

      This is reasonable, but it assumes some other function can do the needed cleanup code or other data massaging just as cleanly. If the goto is being used because finding the value is an error condition, you often have to do certain things as soon as possible in the code so you do not lose important debugging information.

      And, no, exceptions are not part of C, and setjmp/longjmp is, if anything, even less likely to pass code review. An advantage of goto is that you can keep the cleanup code in the same function, visually close to the rest of the logic and sharing the same locals.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    23. Re:One word.. by umghhh · · Score: 1
      goto is just a tool, it is a soft brain that kills.

      I see no problem with GOTs as long as they are used properly. The reason why their use should be restricted is that brainless people left with the choice:

      • use goto when necessary
      • use other ways available in your l. of choice if possible and feasible

      combine the two and use GOTO and other programming methods without thinking producing structureless bulk of code. Resulting monstrous spaghetti like thing may function sometimes but becomes a hell of a trap when used as code base for next design. This 'sometimes' working part is also interesting albeit today this is not of so much concern as people are used to crappy software by now.

    24. Re:One word.. by beelsebob · · Score: 1

      You're dead right about goto being used from a lack of thinking. So much so in fact, that I've so far not found a case where I've wanted to use something goto like, and not figured out a much better representation for my data structures/code soon after.

    25. Re:One word.. by beelsebob · · Score: 2, Informative

      Yes it is, goto requires a label, and thus requires someone reading your code to go hunting for it. Return is known to push control flow to the exit of the function. One obfuscates code, the other doesn't.

    26. Re:One word.. by Anonymous Coward · · Score: 0

      Have you ever tried abusing the try/catch statements?

    27. Re:One word.. by Anonymous Coward · · Score: 3, Informative

      Error handling in C code is my typical example of that. It mostly avoids the need for lots of if statements to make sure that you clean up all that you need to and nothing more.

      There are other ways to go about it, but in general I'm not convinced they are better.

      The most common use of "goto" in that circumstance is to enforce "only one return".

      Which is every bit the pedantic lunacy that goto-hate is.

    28. Re:One word.. by digitig · · Score: 2, Insightful

      as well as some oddly structured loops for which try/catch logic doesn't get you all the way

      Such loops are almost certainly buggy, almost certainly maintenance nightmares and I'll stick my neck out and say certainly unnecessary. The logic needs redesigning. So they are examples of dirty tricks to get code out of the door, as the GOTO poster suggested.

      --
      Quidnam Latine loqui modo coepi?
    29. Re:One word.. by maxwell+demon · · Score: 1

      Similarly, the "there shall be only one exit from a function" is often used as a tautology by some.

      AFAIK they even removed alternate return arguments from Fortran. At the same time, exceptions are added to modern languages, which are noting but a different way to specify alternate return paths. The same is of course true for C's longjmp.

      However, for any language which offers neither exceptions (or similar mechanisms like longjmp) nor alternate return arguments, the "only one exit from a function" is a tautology (i.e. it's automatically true). You probably actually meant return statements inside the function, but that's not an alternate return path, but just a "goto end_of_function" inside the function. You'll end up in the calling code exactly at the same place as with a return at the end.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    30. Re:One word.. by GigaplexNZ · · Score: 1

      What you just described was an implementation detail, not a conceptual difference.

    31. Re:One word.. by Jurily · · Score: 4, Interesting

      But as below says, they make error handling an easier task as well as some oddly structured loops for which try/catch logic doesn't get you all the way

      Ugh. Magic invisible gotos FTW!

    32. Re:One word.. by GigaplexNZ · · Score: 1

      Not all languages have them and even if they do, not all code is exception safe.

    33. Re:One word.. by fbjon · · Score: 1
      It's not the underlying machine code that's the problem, it's the GOTOs in the high-level language that presents maintainability problems. Hell, food just ends up as one paste in your stomach, so why go to the trouble of cooking?

      Also, some GOTOs are not really GOTOs, for example breaking out of a deeply nested loop is properly known as a break of the loop. If you GOTO some other place than immediately after the loop, then you have a "real" GOTO, i.e. going to an arbitrary place in memory.

      Golden rule of programming: software is best written for humans to read and computers to compile, not vice versa.

      --
      True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
    34. Re:One word.. by teac77 · · Score: 1

      but there are consequences... http://xkcd.com/292/

    35. Re:One word.. by Anonymous Coward · · Score: 0

      Nothing wrong with a goto ... as long as it's followed by:

      // TODO: OMGLOLHACK

    36. Re:One word.. by martyros · · Score: 1

      In OS code, it's pretty common to have to acquire several resources which may or may not be available, before doing something, and then releasing all of them. If you acquire some of your resources and one of them fails, you have to release the ones you've acquired so far. Since all the release code is the same, it makes sense (and it's easier to read) to just share the release code, thus (replace '.' with ' ' in your head):
      int* foo(int arg1, char *arg2)
      ..int * ret=NULL;
      ..resource *r1, *r2, *r3;
      ..if(!(r1=acquire(1)))
      ....goto out;
      ..if(!(r2=acquire(2)))
      ....goto out_release_r1;
      ..if(!(r3=acquire(3)))
      ....goto out_release_r2;
      ..ret=use_resource(r1, r2, r3);
      ..release(r3);
      .out_release_r2:
      ..release(r2);
      .out_release_r1:
      ..release(r1);
      .out:
      ..return ret;
      }

      --

      TCP: Why the Internet is full of SYN.

    37. Re:One word.. by Anonymous Coward · · Score: 0

      Such loops are almost certainly buggy

      [citation needed]

    38. Re:One word.. by setagllib · · Score: 1

      If you aren't using RAII semantics, you aren't really using C++, but C+-. If you're using RAII and sane integrity guarantees, exceptions avoid a lot of redundant and bug-prone code.

      --
      Sam ty sig.
    39. Re:One word.. by Anonymous Coward · · Score: 0

      Eh, GOTO can be pretty useful, especially in older languages with no support for things like BREAK / CONTINUE or similar syntax.
      Just place a pointer directly after the end of the loop and check your conditions before (or after depending on Loop type) running a cycle.

      And even then, making small jumps in functions that come from similar, fixed parent functions to decide some values before entering a main function has always been one of my uses. (mainly for the sake of keeping a nice clean function, since i tend to re-use quite a bit of my code for other purposes as well)

      The above is one i use in Autohotkey a lot because it is a bit of a mess when it comes to throwing several key-presses in to one function.
      You have to end up resorting to removing any key modifiers for one, which is absolutely annoying in every way.
      Yes, i could easily write a global function to remove the keys and return key and mods as CSV, but i'm a lazy *(&^@{$.

      It is large GOTO jumps that are horrible.
      Even worse if they are obfuscated because you don't like the particular company you are in.
      Or the absolute worst of them all, the GOTO position is generated dynamically...

    40. Re:One word.. by hairyfeet · · Score: 5, Interesting

      I like the way my former VB teacher put it (and yes I use the occasional GOTO, but then again I learned in the real BASIC-Commodore BASIC) he said "The GOTO is like a chainsaw. yes, some folks can actually make good things, and even make really nice carvings with a chainsaw. most just make a big fucking mess."

      Of course me and him both laughed our asses off when some 19 year old tried to rip off my code and pass it off as his own. After laughing and giving the kid a big F the kid said "How do you know that he didn't steal it from me?". So he asked the kid where he learned VB and which OS and the kid said "Windows 98 and the VB I got from this class!" and the teacher projected the code onto the board and said "Now class, does anybody notice something a little...weird about this code?" and a girl popped up and said "Why are their numbers before the lines, and what is a GOTO?".

      The teach just laughed and said "once upon a time their weren't any GUIs on personal computers. All you got when you turned it on was a blinking CLI and you had to write your own programs, using VERY old syntax. The person who wrote this is used to working in teeny tiny amounts of memory and using the old style, which works just fine if you know what you are doing, but if not it'll blow in your face like Mr. Greene found out when he tried to snatch this code and incorporate it into his own without knowing how it works" he then turned to me after staring at the code for a minute and said "Atari or Commodore?" and I looked shocked and said "Commodore VIC20, but how did you know that?" and he said "because I have been around long enough to have coded on just about everything, and that looked liked Atari or Commodore code. Very efficient, but about as subtle as a chainsaw." which is when he gave me the chainsaw quote.

      So I have never forgotten the chainsaw quote, and while I can wield the chainsaw without making a mess, I saw first hand when others in the class tried to use GOTO what a mess you can make if you don't know EXACTLY what your code is doing. He caught me outside a month later and said "thanks a lot, I hadn't seen a GOTO in ages and then you come along and it spreads like the damned clap. Giving these youngsters GOTO is like handing a monkey a sledgehammer and letting them loose in a bomb factory. There is no doubt they are going to go boom, the only question is when." but what can I say, I'm just an old greybeard that was used to numbered lines and GOTO.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    41. Re:One word.. by CarpetShark · · Score: 1

      int* foo(int arg1, char *arg2) ..int * ret=NULL; ..resource *r1, *r2, *r3; ..if(!(r1=acquire(1))) ....goto out; ..if(!(r2=acquire(2))) ....goto out_release_r1; ..if(!(r3=acquire(3))) ....goto out_release_r2; ..ret=use_resource(r1, r2, r3); ..release(r3); .out_release_r2: ..release(r2); .out_release_r1: ..release(r1); .out: ..return ret;
      }

      Dude. It may be a few clock cycles more efficient than higher-level code, but that's just horrible. I can't imagine many situations (even embedded) where that could be justified these days. Try something like:

      acquire_any(&r1, &r2, &r3);
      use_resource(&r1, &r2, &r3);
      release_all(&r1, &r2, &r3);

    42. Re:One word.. by FourthAge · · Score: 4, Insightful

      Hardly pedantic or lunacy. For example, pick one of the drivers from the Linux kernel, e.g. this one. Look in particular at the "geode_aes_probe" function.

      The structure looks like a pyramid. On one side is the setup phase, on the other side is the cleardown phase. If one of the setup operations fails, then the "goto" jumps to the appropriate cleardown operation and continues from there. If the top of the pyramid is reached, then return #1 (success) is used. Otherwise, return #2 (failure) is used.

      This function could be written in C without using goto. But would it be as easy to read and as easy to maintain? Doubt it. As it is, it's perfectly obvious what you would need to do in order to add a new capability to the driver. Tricks to work around "goto" would only obfuscate the functionality.

      --
      The tao of democracy: the government you can vote for is not the real government.
    43. Re:One word.. by MozzleyOne · · Score: 1

      Write a seperate lookup function, and in that use a return statement. As an added bonus, this makes your original function much easier to follow - you don't have to work out that the nested loop is performing a lookup, the function's name TELLS you that!

      I've never seen a good reason to use goto - maybe when optimising a REALLY critical bit of code - though I can't think of any examples offhand where using better control structures wouldn't generate the same assembler.

      --
      Ayjay on Fedang
    44. Re:One word.. by beelsebob · · Score: 1

      Yep, I think the thing that's missing from this though, is that people who use a chainsaw to carve ice do so only because they can. They do so deliberately because it's harder than the alternatives.

      The same is true for code. Using goto is in general harder, and messier than using decent tools. That's not to say ofc that occasionally you might not want to chop a tree down.

    45. Re:One word.. by lena_10326 · · Score: 1

      The other guy said error handling. I say error cleanup when there are numerous dynamically allocated objects where failures can potentially occur at any stage.

      You wanted a specific example, well here is one. It may be a little contrived but it's something you may find in C code. It simulates a poor man's try/catch in C and is syntactically more succinct than it would be using nested functions or nested "if" statements. You could wrap the code in a do { } while(0) loop and use breaks, but that would add useless syntax to accomplish the same thing. The logic is mostly linear and only does one implicit return. You can also add an error string and assign it at each error point (left out for brevity).

      int myfunction(const char *inFile, const char *outFile) {
      FILE *in = NULL;
      FILE *out = NULL;
      char *buf = NULL;
      stats_type *stats = NULL;
      int rc = -1;

      if (file_exists(outFile))
      goto error_exception;

      if (NULL == (in = fopen(inFile,"r")))
      goto error_exception;

      if (NULL == (out = fopen(outFile,"w")))
      goto error_exception;

      if (NULL == (buf = (char*) malloc(someMagicSize)))
      goto error_exception;

      if (NULL == (stats = stats_new()))
      goto error_exception;

      while (fread(buf, someMagicSize, sizeof(char), in) == someMagicSize) {
      stats_datum* record = stats_new_datum(buf);

      if (record == NULL)
      goto error_exception;

      stats_store(record);
      }

      if (ferror(in))
      goto error_exception;

      stats_print(stats, out);
      rc = 0;

      error_exception:
      if (in) fclose(in);
      if (out) fclose(out);
      if (buf) free(buf);
      if (stats) stats_free(stats);

      return rc;
      }

      --
      Camping on quad since 1996.
    46. Re:One word.. by Decameron81 · · Score: 1

      Using multiple exit points (returns) in a single function is, IMHO, worse than using GOTO.

      It makes you have to execute your clean up code in each exit point you have, which means you have to repeat code. You have to keep the cleanup code always synchronized accross all exit points.

      --
      diegoT
    47. Re:One word.. by 91degrees · · Score: 3, Insightful

      Surely you could do that as a nested if.

      Whether that is better or not is subjective. "Goto considered harmful" has become dogma, but while your example is a very good example of goto used well, most programmers would use it to write spaghetti code. Barring the use of the keyword means that it does only get used by people who know exactly what they're doing.

    48. Re:One word.. by Decameron81 · · Score: 1

      I agree with you, GOTO for cleaning up code is much better than multiple exit points in the same function and cleaning up a gazillon times.

      --
      diegoT
    49. Re:One word.. by martyros · · Score: 1

      That might work, except that the exact list of resources and the order they're acquired are usually particular to the function. They may include incrementing reference counts, grabbing spinlocks or mutexes, allocating memory, mapping memory, even copying data from / to userspace (which may fail). You'd have to write an acquire_any() individually for each function you're writing. Generally, having the chiastic structure makes it easy to double-check that you've handled all of the releases properly.

      --

      TCP: Why the Internet is full of SYN.

    50. Re:One word.. by MrSteveSD · · Score: 1

      Breaking out of a deeply-nested loop, as can happen when you're looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.

      But then you can surely just have your array search as a function and return the information you need from the function. So in the function itself when you find the element you want, you can just return the index. I don't think I've ever had to use a goto in my code, and when I've been tempted it tends to be an indication that I need to rethink things.

    51. Re:One word.. by dargaud · · Score: 1

      Often, goto is the best solution to given problem.

      When coding state machines in C, I don't see too many ways around gotos but I'd be curious to hear them.

      --
      Non-Linux Penguins ?
    52. Re:One word.. by Hattmannen · · Score: 2, Funny

      Such loops are almost certainly buggy

      [citation needed]

      That seems a bit redundant. You just cited him, didn't you? I get the strangest feeling of recursion when someone quotes somebody else and asks for a citation...

      --
      People are not wearing enough hats.
    53. Re:One word.. by MrSteveSD · · Score: 1

      The goto statement is very useful. Your dislike of it is irrational. Do you even know why you do not like it? Often, goto is the best solution to given problem.

      The point of avoiding goto statements is that it decreases readability. Things can rapidly descend into spaghetti code if the flow jumps all over the place because of gotos. Usually a rethink can eliminate your need for a goto statement. For example, if there is a section of your code you need to jump out of, put that code in a function instead and return from the function instead of jumping out.

      I'd be interested in seen an example of when you have used goto, because there usually tends to be a better way.

    54. Re:One word.. by Anonymous Coward · · Score: 0

      I once saw a goto used like this

      if( condition a)
      {
      IfPart:
      }
      else
      {
              if( condition b)
              {
                      goto IfPart;
                }
      }

      *shudder*

      Gotos are handy if you are writing a byte code machine for a game engine scripting system though...

    55. Re:One word.. by FourthAge · · Score: 5, Insightful

      I'd agree with all of that. Like C itself, goto is a powerful tool that is easily misused by beginners, but is still very useful in the right circumstances.

      --
      The tao of democracy: the government you can vote for is not the real government.
    56. Re:One word.. by Adovid · · Score: 1

      The problem with GoTo was pointed out by Dijkstra. It makes it hard to analyze and read a program which uses goto statements. Higher level languages are supposed to abstract the goto statements away so when code jumps to another location in memory it's in a scenario that is clearly understood. The purpose of language is communication, programming languages are no different. Besides, think of the big picture-- hashing, memoization, heaps, trees, all of the tried and true algorithms we have at our fingertips. Given increasingly large data sets an effective use of these ideas will outperform the short sighted approach. In the world of computers hardware moves data so fast that these kind of optimizations mean so much more than a few cycles saved for using a simple instruction. To implement these more holistic approaches you have to design in a way which makes sense, so that you can analyze everything you are doing as part of the bigger picture.

    57. Re:One word.. by Hognoxious · · Score: 1

      I don't see why it's specifically a nested if. What you would need to do is to enclose all "normal" code in an if, then when there's an error you set a flag or flags so that it skips until the point where the cleanup/exit starts.

      Bear in mind that there could be many error conditions which need to clean up from different points. It'd be much more of a mess. I'd use a goto.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    58. Re:One word.. by Nursie · · Score: 1

      I only ever implemented one, and it was a huge while loop containing a big switch. That was when I was still a little wet behind the ears though.

    59. Re:One word.. by Aladrin · · Score: 2, Informative

      I have not used a 'goto' statement in about 15 years now. But it's not some irrational fear. It was all due to someone saying 'there's no situation that requires a goto' and 'goto statements make code hard to read'.

      And after I used goto a little more, I realized they were correct. In any good, modern language, 'goto' is completely unnecessary and makes your code harder to read.

      If you're breaking out of a loop, you should use 'break'. If you're continuing a loop, 'continue'. If you're handling an error, throw an exception. If you're calling another piece of code, make that code a function and call it properly.

      --
      "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    60. Re:One word.. by grumbel · · Score: 1

      That depends on the language. In C goto is used a lot as a simple function-scope exception mechanism, as the language doesn't have real exceptions and doesn't support RAII there really isn't a better way then to use goto to handle cleanup after an error. Nested if's would of course also do, but lead to a lot of code duplication.

      In C++ on the other side you have exceptions and RAII und thus no longer need the goto-trick.

      Of course goto can be abused as a replacement for 'for' and 'while' loops as done in early BASIC dialects, but I haven't seen such use of goto in a long long while. Even inexperienced programmers no longer code stuff like that, as their first language no longer is BASIC.

    61. Re:One word.. by Anonymous Coward · · Score: 0

      The GOTO was shunned in many programming courses because newbies would abuse it and use it to create spaghetti. Thats why it was shunned in intro programming courses. Of course, by the time you say hello to assembly language, Jump, jump relative, etc, is all basically GOTO except that its at the machine level, and since there isn't anything else, you use it (no sparky, there is no do-until or for-do, not in assembly). Also, in operating systems, there are data structures needed that simply don't exist in C (very few operating systems exist in 2009, that aren't written in C (and I'm not talking about that bane called C++). Thats why some have their notion of GOTO. For the last 20 or so years, all light programming I've done (non-system-level) don't require goto's. I don't hate them, I just know they have their place. At the system level, there are places where they save 300 lines and are perfectly valid. I've read in detail operating system source code, and see it every once in a while. Not a problem. If you can code at that level, you are already using pointers and are pushing addresses into the program counter (and for you newbs who don't know what a CPU program counter register is, you don't have the chops), then no problem.

    62. Re:One word.. by Anonymous Coward · · Score: 0

      I see similar stuff from time to time, and each time it isn't replaced by something on the order of

      return foundIt;

      I die a little on the inside.

    63. Re:One word.. by beelsebob · · Score: 2, Funny

      I agree, if you need cleanup code... But I don't write code with side effects, so there's no problem whatsoever. No side effects means no clean up.

    64. Re:One word.. by TheRaven64 · · Score: 1

      And then make it static inline and your compiler will emit exactly the same code as if you used goto, but the next person who reads your code won't try to stab you for giving them nightmares.

      --
      I am TheRaven on Soylent News
    65. Re:One word.. by binkzz · · Score: 0, Troll

      As a programmer it scares me genuinely to see your post get rated +5 Informative. GOTOs have no place in man made code. There are so many reasons why not to use GOTOs, and only very few situations that GOTOs make for cleaner code (specifically, the usually implemented break, last and next GOTO surrogates). If one of the people in my team uses GOTOs I tell them off.

      A brief study of the pros and cons: http://www.stevemcconnell.com/ccgoto.htm

      As you can tell from that, and many other sides, there are no major pros to using GOTOs, but very major negatives. Many modern languages don't support GOTO, or only include it to support machine generated code (ADA).

      Have you counted the number of GOTOs in the linux kernel?

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    66. Re:One word.. by Anonymous Coward · · Score: 0

      When you're a hammer, everything is a...

    67. Re:One word.. by binkzz · · Score: 0

      > It doesnâ(TM)t matter what the compiler does; source code is for humans.

      Source code is for compilers. English is for humans.

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    68. Re:One word.. by Antique+Geekmeister · · Score: 1

      Have you ever tried to cut ice cleanly without a powerful and potentially dangerous tool? For large scale work on good, hard ice, chain saws are very efficient.

      I'm thinking back to some winter work at a logjam on a relative's property, a few years ago. I brought them lunch and stayed out of the way, but they did indeed use chain saws effectively the ice that had formed on the downstream side of the barrier and on various projecting pieces of debris.

    69. Re:One word.. by bytesex · · Score: 1

        while (1) {
          switch (nextheader) {
          case 0:  fprintf(stderr, "-------- Hop By Hop\n"); goto OPTION;
          case 43: fprintf(stderr, "-------- Routing\n"); goto OPTION;
          case 44: fprintf(stderr, "-------- Fragment\n"); goto OPTION;
          case 50: fprintf(stderr, "-------- ESP\n"); goto OPTION;
          case 51: fprintf(stderr, "-------- Auth. header\n"); goto OPTION;
          case 60: fprintf(stderr, "-------- Destination options\n"); goto OPTION;
      OPTION:
            {
              unsigned nhd = payload[0];
              unsigned len = payload[1];
              unsigned siz = (len + 1) * 8;
              fprintf(stderr, "nexthd.: %u\n", nhd);
              fprintf(stderr, "noctets: %u\n", len);
              if (siz <= size) {
                payload += siz;
                size -= siz;
                nextheader = nhd;
              } else {
                fprintf(stderr, "WARNING: Exceeding given data.\n");
                goto ENDOPTIONS;
              }
            }
            continue;
          case 6:
            netdbg_ipv6_tcp(packet, payload, size);
            return;
          case 17:
            netdbg_ipv6_udp(packet, payload, size);
            return;
          case 58:
            if (size >= 8) {
              netdbg_icmpv6(packet, payload, size);
            } else {
              fprintf(stderr, "WARNING: No further processing.\n");
            }
            return;
          default:
            fprintf(stderr, "Unknown type %d: No further processing.\n", nextheader);
            return;
          }
        }
      ENDOPTIONS: ;

      --
      Religion is what happens when nature strikes and groupthink goes wrong.
    70. Re:One word.. by TheRaven64 · · Score: 3, Insightful

      Actually most exception handling constructs are even worse than goto, because they can unwind the stack an arbitrary amount. This is because they are taken from languages like Lisp and Smalltalk, which had accurate garbage collection and stack introspection and so could be used safely, and plonked into languages which have neither. In Java they're not too bad because you have to explicitly declare every exception that you can throw and so they become part of the interface, but they are horrendous in something in the C family. There's a nice Raymond Chen article where he writes the same bit of code with and without exceptions, and it's clear where the bug is in the exception-free implementation (error value ignored) but with exceptions it's very difficult to spot and the number of possible code paths grows alarmingly.

      Goto in C is not like goto in BASIC or many languages from the '70s and earlier, which was basically a higher-level wrapper around a jump instruction. In C, a goto statement is only allowed to jump within the current function, so it doesn't break structured programming too badly. Exceptions and longjmp(), do. Longjmp(), as it's traditionally implemented, is the worst because there is no way for any code in intervening stack frames to handle cleanup and so it's almost impossible to use without causing resource leaks of some kind. Non-local exceptions are almost as bad, because they hide multiple return paths. Sometimes it's cleaner to have two or three different return statements in a function, but with exceptions every single function call is a potential return path unless you wrap every single call in a try / catch block.

      --
      I am TheRaven on Soylent News
    71. Re:One word.. by MozzleyOne · · Score: 1

      With a good compiler, you shouldn't really even have to do that!

      I try to write all my code as readable as possible, then, IF it proves to be slow (in a release build as well - so many people I know infer release speed from debug speed), I'll go investigate further.

      It's the application of the 80/20 rule - 80% of the time is spent in 20% of the code (in my experience, it could even be a 90/10 rule). Why do people try to optimise 100% of their code?!

      --
      Ayjay on Fedang
    72. Re:One word.. by maxwell+demon · · Score: 1

      Well, if you are programming C++ (the proper way), RAII handles that for you.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    73. Re:One word.. by TheRaven64 · · Score: 1

      It's worth noting that Dijkstra's goto is not the same as the C goto. He was talking about languages where goto is the primary method of flow control and allows you to jump anywhere in a program. In contrast, C's goto only allows you to jump within a single function, and so does not make it difficult to reason about code because it's just another local flow-control mechanism. It's usually not the best solution in C, but it's not particularly evil.

      --
      I am TheRaven on Soylent News
    74. Re:One word.. by aquila.solo · · Score: 1

      That looks like an XOR to me... Not the cleanest obviously, but understandable with all of a minute looking at it.
      Anybody care to support or dispute that?

    75. Re:One word.. by PhilHibbs · · Score: 1

      Clearly you are unaware of the danger inherent in using GOTO.

    76. Re:One word.. by sanosuke001 · · Score: 1

      wouldn't a switch be just as easy? just leave out the break in each section and it'll flow through everything below it. Set a flag in each of those if's. have the first switch do your return 0 (ie. flag == 0) and the rest do what they do now.

      I know the extra byte in memory plus initializing/updating it might upset some but it would be just as clean and would not require the use of the goto. Aside from hearing people like or dislike goto's, I never saw the harm. If you can't debug code that has a couple gotos in it, then you probably shouldn't be programming.

      --
      -SaNo
    77. Re:One word.. by petes_PoV · · Score: 1
      and Dijkstra was wrong

      What he was talking about was a limitation in the documentation of the code - not the code itself. The workaround to the documentation problem was to "prohibit" the use of GOTO statements. These days things have moved on. We have much better tools for tracing code execution and keeping tabs on the software environment. These make the fashion for avoiding GOTOs obsolete as the problem has (effectively) gone away - if it even ever existed at all, except in the minds of a few ivory-tower types who were more concerned with having pretty looking constructs than workable and efficient software.

      Sadly, software courses are taught by academics who "don't get out much" and probably haven't written a whole lot of real-world code. They are herd animals, much more concerned with their own academic reputations than educating students in the practicalities of the real world (which most of them know little about). Since the next generation of lecturers is taught by the last generation, once an old-wives-tale like this gets into the meme-ome, it's very hard to shift it - despite all the evidence and experience that shows it to be completely bogus.

      --
      politicians are like babies' nappies: they should both be changed regularly and for the same reasons
    78. Re:One word.. by consonant · · Score: 1

      Seeing as how I'm getting flamed for bringing up what is obviously a touchy topic, two things have to be said:

      1. From which point in my post are people assuming I think GOTOs are evil? It was largely a neutral statement on a controversial programming construct.
      2. Guns don't kill and GOTOs don't make bad code, people do.
    79. Re:One word.. by Wildclaw · · Score: 1

      It makes you have to execute your clean up code in each exit point you have

      Only if you use a language that doesn't support the try-finally concept. And there you pretty much have the biggest reason to use goto. Namely, to emulate very much needed control structure features that doesn't exist in the language you are currently forced to use.

    80. Re:One word.. by Rockoon · · Score: 1

      I dont believe that it was either Kernighan or Ritchie, unless we are thinking of seperate goto opponents. The opponent I am thinking of is Edsger Dijkstra.

      If GoTo is 'considered harmful' then isn't Object/Event Spaghetti far more harmful? When looking at modern source code, its often impossible to figure out program flow, which was the exact same arguement against GoTo.

      I'm sure the OOP proponents will now chime in and say that the seperation of duties principle means that you dont really need to grasp program flow.. and all I have to say to that is that there is a difference between theory and practice.

      In practice there is external state and side effects, where Big Giant Function can be proven to be correct (even if it uses GoTo's) without the miles of safe-guard code that a Big Giant Object Graph would require for the same proof.

      --
      "His name was James Damore."
    81. Re:One word.. by maxume · · Score: 1

      The obvious reply to this is 'goto hell;'.

      Note that I don't actually feel that sentiment.

      --
      Nerd rage is the funniest rage.
    82. Re:One word.. by robfoo · · Score: 5, Insightful

      I can't figure out if I'm the only sane one or the only crazy one. Especially given the 'pyramid' referred to - I don't see a pyramid unless it's rewritten to use nested ifs.

      To me, nested ifs are much easier to read - they convey the meaning/intent of the code a lot better. As in 'if this function call works, then do this. Otherwise, just clean up and exit'

      How is this so hard to understand?

      geode_aes_probe(struct pci_dev *dev, const struct pci_device_id *id) {
              int ret;

              if ((ret = pci_enable_device(dev)))
                      return ret;

              if (!(ret = pci_request_regions(dev, "geode-aes"))) {
                      _iobase = pci_iomap(dev, 0, 0);
                      if (_iobase == NULL) {
                              ret = -ENOMEM;
                      }
                      else {
                              spin_lock_init(&lock); /* Clear any pending activity */
                              iowrite32(AES_INTR_PENDING | AES_INTR_MASK, _iobase + AES_INTR_REG);
                              if (!(ret = crypto_register_alg(&geode_alg))) {
                                      if (!(ret = crypto_register_alg(&geode_ecb_alg))) {
                                              if (!(ret = crypto_register_alg(&geode_cbc_alg))) {
                                                      printk(KERN_NOTICE "geode-aes: GEODE AES engine enabled.\n");
                                                      return 0;
                                              }
                                              crypto_unregister_alg(&geode_ecb_alg);
                                      }
                                      crypto_unregister_alg(&geode_alg);
                              }
                              pci_iounmap(dev, _iobase);
                      }
                      pci_release_regions(dev);
              }
              pci_disable_device(dev);

              printk(KERN_ERR "geode-aes: GEODE AES initialization failed.\n");
              return ret;
      }

    83. Re:One word.. by microTodd · · Score: 2, Insightful

      You were very, very lucky, in an awesome way. None of my programming teachers were EVER that savvy.

      --
      "You cannot find out which view is the right one by science in the ordinary sense." - C.S. Lewis on Intelligent Design
    84. Re:One word.. by Anonymous Coward · · Score: 0
    85. Re:One word.. by Derleth · · Score: 2, Insightful

      So formatting is worthless, then? And why do we have so many languages, many of them domain-specific? Compilers don’t care about how understandable the metaphors are or how many lines are needed to do a specific thing.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    86. Re:One word.. by Derleth · · Score: 1

      OK, so how do you handle deallocation of resources upon finding an unrecoverable error midway through the function? It seems a lot more readable and maintainable to have all deallocation code in one location near the end of the function, as opposed to duplicated wherever an error might be found, which means at least one copy of the code is likely to be wrong, or shunted off into its own function, which would force all of the local variables holding dynamic resources to be made into globals or similar.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    87. Re:One word.. by Derleth · · Score: 1

      From which point in my post are people assuming I think GOTOs are evil?

      From the context of a 40-year-old free-floating flamewar over the topic of gotos, which reignites every time the construct is mentioned, even in passing. It is one of the hardiest perennials in programming discourse.

      --
      How can you use my intestines as a gift? -Actual Hong Kong subtitle.
    88. Re:One word.. by geminidomino · · Score: 5, Funny

      Pyramid? It looks more like the players' ship sprite from Galaga, rotated 90 degrees...

      Damn, now I want to play Galaga...

    89. Re:One word.. by FlyByPC · · Score: 1

      I often program in PIC assembly. While it's possible to avoid (most) GOTOs, it's difficult to do so and have the code look readable.

      To me, GOTO and call/return are two distinct styles of programming (FSM-style and function-style). Mixing the two can be powerful, but it can also make a big mess. Programming on the PIC, I try to limit the GOTOs to specific instances where they are really implementing a small for or while loop -- including the one last GOTO at the bottom to keep the program counter from falling off the end of the code.

      Of course, the whole call/return story gets more complicated on the smaller 8-bit PICs, since they only have eight levels of hardware stack, and no overflow/underflow checking, unless you're running in simulation...

      --
      Paleotechnologist and connoisseur of pretty shiny things.
    90. Re:One word.. by Ash+Vince · · Score: 1

      The best example of when to use goto in C is when you want to produce an endless loop. This is a pretty rare occurrence but there are times when the program is never designed to exit under normal conditions. Mostly this comes up in embedded devices. On these occasions you are fairly limited and any sort of while loop with a null exit condition I consider to be an ugly hack.

      The anti-goto rhetoric you hear at university is because it is far too easy to make a complete horrendous mess using goto statements and the occasions when it is the correct tool are very few and far between. It is easier to tell noobie programmers that they should never use goto then let them figure out the one or two exceptions to this when they have a few years experience.

      --
      I dont read /. to RTFA, I read /. to offend people in ignorance.
    91. Re:One word.. by geminidomino · · Score: 4, Funny

      So formatting is worthless, then?

      No, formatting is for successors and maintainers. As fellow coders, they're not human, strictly speaking.

    92. Re:One word.. by ArsenneLupin · · Score: 0

      I like the way my former VB teacher put it (and yes I use the occasional GOTO, but then again I learned in the real BASIC-Commodore BASIC) he said "The GOTO is like a chainsaw.

      pot. kettle. black.

      In a discussion about financial instruments, I'd never dare to quote Bernie Madoff...

    93. Re:One word.. by ArsenneLupin · · Score: 2, Informative

      That's why God invented the finally clause. Any cleanup that absolutely cannot be skipped goes into finally.

    94. Re:One word.. by chord.wav · · Score: 1

      Black holes are GOTOs. If it's good for the universe, why shouldn't they be good for you?

    95. Re:One word.. by TheRaven64 · · Score: 1

      Well, you should make it static if it's not used outside of the file anyway, because otherwise you're exporting it into the global symbol table which can cause problems and pollutes the interface (and people reading it will think 'why is this public, where else is it used?'). Inline is not so important. Modern compilers ignore it for optimisation; they'll choose whether to inline it or not, but it's useful for documenting the code so people reading it know that you expect it to be inlined.

      For all of the people over-optimizing: It's very easy for a compiler to inline functions, but it's incredibly difficult (polynomial complexity) for it to extract shared code into a shared function. Even ignoring copy-and-paste bugs, cache contention on a modern CPU means it's more likely that duplicated code will be slower - and a decent compiler will handle the duplication for you in cases where it won't be.

      --
      I am TheRaven on Soylent News
    96. Re:One word.. by basiles · · Score: 2, Insightful

      Every control structure in C++ is equivalent to either a goto or jnz plus some syntactic sugar.

      This is almost true, but I see one important exception: the exception machinery in C++ (that is the compilation of throw and catch C++ statements) is not exactly a goto (and neither is longjmp in C). And of course, any (method or function) call and return is not exactly a goto neither. Exceptions,calls and returns also change the stack pointer.

      I would also notice that computed goto (i.e. the goto *p; GNU extension of C) is compiled as an indirect jump.

      A more interesting concept is continuation Regards

    97. Re:One word.. by EvanED · · Score: 4, Informative

      How is this so hard to understand?

      It's not. But nor is code that uses goto in the idiom that FourthAge posted above.

      My objection to that code is that if you do even just three or four allocations, you start getting very large indentations pretty fast, especially if you like 8-character indentations. (They get pretty long even with 4, which is what I like!) This causes a problem if you restrict yourself to 80-columns.

      Arguably this is a problem with restricting yourself to 80 columns, but that's not entirely unreasonable even if I'd rather the limit be ~100. But guess how many your code uses? Your longest line is 109, longer even than my longer preference. Even if you use 4-character indentations, your longest line is still 80 characters.

      If you reformat your code to use 8-character indentations and 80-character column limits, your code would become a bit uglier as you'd have to wrap four lines (a couple of which don't really have a good breaking point), and hence a little harder to understand on its face.

      By contrast, the original code fits entirely within 80 characters (admittedly only just) without anything remotely like an awkward line break.

      Further, in some sense it doesn't entirely follow the flow of the code. Perhaps this is a vice and not a virtue, but I tend to think of places where there's an unusual condition (like a failed allocation) as not on the same "level" as normal control flow. In this sense, I would think of that procedure as basically linear "with some provisions for exceptional conditions". In that sense, your proposal of the cascaded ifs doesn't really match my mental model of how the code behaves -- the indentation of the normal code changes depending on how many exceptional conditions might arise, and there's not really any reason why it should by that model. By contrast, the original code matches it.

      (Incidentally, "linear with some provisions for exceptional conditions" is basically how I'd write it either in a language that supports exceptions or a language that has RAII. In the former case, there's a decent chance do just one try block for the body of the function, and in the associated catch test to see if each item is allocated in turn. (This doesn't match the structure of the real code exactly, but it's closer to it than it is to your nested-if code.) In the latter case, you'd have basically the real kernel code except that the deallocation would be in the RAII objects' destructors. Again, no nested ifs.)

    98. Re:One word.. by binkzz · · Score: 1

      Formatting is useless if you want to be able to keep track of your code, but eventually it's all for the compiler.

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    99. Re:One word.. by CrashNBrn · · Score: 1

      Like when doing quick-n-dirty scripting.
      1) AutoHotKey Loops:: to stay within the loop and keep checking a piece of the loop until the condition is met to 'break'.

      2) Batch.CMD:: to get out of the script, GOTO:EOF

    100. Re:One word.. by binkzz · · Score: 1

      Show me your code and I'll show you an alternative.

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    101. Re:One word.. by Maximum+Prophet · · Score: 1

      As long as the gotos only go down, i.e. like a return or break, there is no spaghetti code. It's when the gotos go up, down and sideways that the code gets bad.

      --
      All ideas^H^H^H^H^Hprocesses in this post are Patent Pending. (as well as the process of patenting all postings)
    102. Re:One word.. by azgard · · Score: 1

      Please see above my example. Sometimes not to use goto is impossible if you also want to avoid duplication of the code.

      And of course, I am aware of http://en.wikipedia.org/wiki/Structured_program_theorem. But seriously, I challenge you to write my example more succintly without goto.

    103. Re:One word.. by mdwh2 · · Score: 1

      Yes it is, goto requires a label, and thus requires someone reading your code to go hunting for it.

      How is this different to "Calling a function requires you to go hunting for that function"?

    104. Re:One word.. by gid · · Score: 2, Insightful

      Heh, I rewrote it the exact same way--before I scrolled down to this comment. Of course the 8 space indents make it a bit wide, but really, who uses an 80 column display anymore?

    105. Re:One word.. by Maximum+Prophet · · Score: 1

      I do this all the time.
      for (;;) {
      }

      Endless loop in C, with no gotos. Anyway, as long as the gotos only go down, you're not going to get spaghetti code.

      --
      All ideas^H^H^H^H^Hprocesses in this post are Patent Pending. (as well as the process of patenting all postings)
    106. Re:One word.. by Bakkster · · Score: 3, Insightful

      You use gotos when the normal control structures are inadequate somehow.

      This is the heart of the issue: control structures are a well defined, easy to follow, hard to fuck-up subset of the things you can do with goto. If you can do it reasonably with a control structure, you shouldn't use goto, because it makes your code more readable. If you can't, then you should consider if your program should be restructured (which is why goto is dangerous to novice programmers). If not, then you can use a goto.

      Of course, all bets are off when you're scraping for clock cycles with machine code, but that's not necessary most of the time.

      --
      Write your representatives! Repeal the 2nd Law of Thermodynamics!
    107. Re:One word.. by ottothecow · · Score: 1
      --
      Bottles.
    108. Re:One word.. by Anonymous Coward · · Score: 0

      I would say that code has a bug in it? If the pci enable fails, it returns the error code, but never does the printk() like all the other errors states do letting you know that it failed initializing the driver.

    109. Re:One word.. by MBGMorden · · Score: 1

      I've done similar.

      Basically just

      while (1)
      {
      }

      When done this way I'll usually have code inside the block that terminates the loop manually when needed, but I try to avoid it in general is just about any loop that need to break can be handled using the condition specified up top.

      It did take a while to get myself away from thinking about goto's though - my first bit of programming I learned in BASIC (and I had some really, really bad habits that formed from just figuring stuff out when I didn't know any better), and so I used them all the time. After starting Java in college though, I eventually just stopped introducing goto's as a possible solution to anything, and I've still not hit a problem that I absolutely needed them for.

      --
      "People who think they know everything are very annoying to those of us who do."-Mark Twain
    110. Re:One word.. by hesaigo999ca · · Score: 1

      I totally agree, goto is not a bad thing,...getting reference to the address it is jumping to IS. The problem is when juniors start using it without thinking of the implications of where it is being used especially if you have looping etc... otherwise it is just another piece of code, like if else, or even do while...

      nothing wrong with GOTO places..

    111. Re:One word.. by dna_(c)(tm)(r) · · Score: 1, Funny

      Why are their numbers before the lines, and what is a GOTO?

      once upon a time their weren't any GUIs on personal computers.

      Don't GOTHERE.

    112. Re:One word.. by ekgringo · · Score: 1

      Maybe he's worried that it won't fit on punch cards.

    113. Re:One word.. by CastrTroy · · Score: 1

      Obviously, some programming constructs are a lot more sugary that others, and have been put in simply to provide a work around so that you don't have to use goto's. One would probably never write a for or while loop using only goto's, but compare an "Exit While" statement from VB.Net, and compare it to the GoTo equivalent. There's isn't much difference in one being more complicated than the other. The Exit While statement isn't even necessary, unless you have some weird fear of GoTo's, there's no reason to even use it, or for it to be there in the first place.

      --

      Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
    114. Re:One word.. by inviolet · · Score: 2, Informative

      From the linked article:

      People have asked why I don't like programming with exceptions. In both Java and C++, my policy is:

      • Never throw an exception of my own
      • Always catch any possible exception that might be thrown by a library I'm using on the same line as it is thrown and deal with it immediately.

      I have done code that way, before exceptions came into vogue. To do it right, you've got to have many many many error-checking if() statements after every call to any function that could fail. That could maybe be done as neatly as with exception-handling, if one was ever careful to maintain one's error-codes in a single numeric heirarchy, so as to allow 'families' of errors. The error-checking statements can then select for specific errors or for families of errors, like this: if (errorCode & ERROR_FAMILY_FILEIO).

      But that is a lot of work, and the code won't be any cleaner than with exception-handling. In fact it will be uglier because you can no longer just call a bunch of functions in a row without checking returns, allowing a single exception-handler at the bottom to catch any errors it thinks it can handle.

      Nor is the author correct in contending that 'throw' is somehow less visible or less handy or less maintainable than 'return'.

      And he won't get the very very nice exception-handling support that some languages like C# offer.

      --
      FATMOUSE + YOU = FATMOUSE
    115. Re:One word.. by MikeBabcock · · Score: 3, Funny

      If you were going to do that without goto, use a while with a break instead of ugly nested ifs.


      while(1)
      {
              if (!start_condition) break;
              action1();
              cleanup1();
              if (!test_condition1) break;
              action2();
              cleanup2();
              if (!test_condition2) break;
      }

      And so on ... it basically gets you exception handling formatted code. Of course, goto is probably still cleaner :)

      --
      - Michael T. Babcock (Yes, I blog)
    116. Re:One word.. by Unoti · · Score: 1

      ...but the next person who reads your code won't try to stab you...

      The important optimization here is making the code human readable and more self documenting. You're right though, premature optimization is a bad idea, but making the code readable from the start is a great idea.

    117. Re:One word.. by Lisandro · · Score: 1

      A switch would do perfectly fine (besides the extra variable), but in this context, the goto structure is just as readable and clean. In fact, that's basically what the switch statement does :)

      I completely agree though, goto's are a tool that their place and uses. This is one of them.

    118. Re:One word.. by russotto · · Score: 1

      When coding state machines in C, I don't see too many ways around gotos but I'd be curious to hear them.

      Almost every state machine I've coded in C has had the general structure


      while (state != endstate)
      {
          switch (state)
          {
          case state1:....
                                  state= someotherstate;
                                  break;
          case state2:....
                                  state = adifferentstate;
                                  break;
          default:
                  error("You broke the state machine");
          }
      }

      No need for goto, though occasionally it comes in handy.

    119. Re:One word.. by Anonymous Coward · · Score: 0

      "Fit the strategy to the tool"
      Correct, hammers and screw drivers are both useful tools and both come in various flavors to fit the intended application. However the sledge hammer is not the appropriate tool for driving a pan head screw. The danger is that some inDUHvidual will try.

    120. Re:One word.. by Anonymous Coward · · Score: 0

      For example, pick one of the drivers from the Linux kernel, e.g. this one [sourceforge.jp]. Look in particular at the "geode_aes_probe" function.

      I misread "geode_aes_probe" and just about spit my breakfast on my screen.

    121. Re:One word.. by Anonymous Coward · · Score: 1, Informative

      This'll add the loop code for something that will never loop, even on an optimizing compiler (How will it know that you'll definitely break out at some point?)

      Besides, cleanup1() will almost certainly have to wait until after action2() in most cases. I'd say increase cleanup_stage for every action performed, then use a switch() {} with no breaks

      case 2: cleanup2();
      case 1: cleanup1();

      but that's just goto with a fancy wrapper.

    122. Re:One word.. by QuoteMstr · · Score: 1

      The canonical way to write an endless loop is for(;;) { ... }.

    123. Re:One word.. by Anonymous Coward · · Score: 1, Informative

      1. you quickly will run out of indentation space, unless you use a shallow indentation, which is a readability problem of its own. The goto-variant allows the "meat" of the function to be just a couple indentation levels in.

      2. If you later add another initialization step, you have to re-indent everything. Even if your editor makes this easy, you'll end up with a huge .patch file which will be painful to merge with any other changes to that function

      3. I actually prefer your style for simple cases (2-3 steps) but sometimes when doing kernel work you end up having to do lots of init/cleanup steps and the goto-style starts to become MUCH more readable than deep-indentation. Basically the goto-style scales to any number of init/cleanup steps while the nested variant would be unworkable with >8 steps

    124. Re:One word.. by Anonymous Coward · · Score: 0

      Your example function has the advantage of being small and easy to read. Now jump 20 years in the future.
      I would point to another example, a real case in our code base.
      This C function started all small and cute and readable in the 80's with a single GOTO for cleanup on failure. As the product grew code was added, all kinds of "goto lovers" experienced coders but also inexperience junior coders worked in there. They added more goto for special errors. More variables for quick fixes on release rush. The few goto present forced to add more variables and more gotos for some exceptional and temporary fixes (that stayed forever).
      When I found this function it had 12,000+ lines. It starts with 100+ local variables and uses another 200+ global vars declared just before it. I found a comment dated from 1992 and another from 2006 in there.
      Of course our in-house "goto lover" finds this normal "maybe a bit long but that's life". He has no has real friends in the team because maintenance in his code takes 3 times longer than in anyone else. No one wants to team work with him because of his bad habits.
      And of course he always boasts on how useful and practical goto usage can be, and he always points at his latest marvel super-efficient algorithm that any junior would mess up in a minute.
      A good coder writes code for the low-cost junior coder that will learn the trade doing maintenance in that code. Anything else I do not hire.

    125. Re:One word.. by Anonymous Coward · · Score: 0

      A more elegant solution is to extract this deeply nested search loop to a function and simply return when the desired item is found.

    126. Re:One word.. by martas · · Score: 1

      [pretty much] anything you can do using GOTO's, you can also do by making small functions that accomplish only one or two tasks. personally, the only time i can think of when a goto would be useful for me is when i have deeply nested for loops, and something happens that makes me want to break out of all of them. this can be accomplished in 2 ways other than GOTO - either have the for loops in a dedicated function and return;, or check a flag at the end of each loop, and break if it's set.

    127. Re:One word.. by dkf · · Score: 1

      So I have never forgotten the chainsaw quote, and while I can wield the chainsaw without making a mess, I saw first hand when others in the class tried to use GOTO what a mess you can make if you don't know EXACTLY what your code is doing.

      If you want a real coding weapon of mass destruction, try the computed GOTO in a language with numbered lines. Get it wrong, and you've no idea what instruction is going to run next...

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    128. Re:One word.. by dcollins · · Score: 3, Informative

      "How is this so hard to understand?"

      For me, it's hard to understand because your most highly indented lines wrap off the edge of the window, back to the left margin, wrecking the indentation cues. In an IDE, it sets a limit on how many conbditions you can check before having to scroll around to see the whole function.

      I used to work at a company where this was the standard and I was never fond of it.

      --
      We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
    129. Re:One word.. by Anonymous Coward · · Score: 0

      who uses an 80 column display anymore?

      About every unix hacker on the planet. I still consider any source code that will not display with correct formating on an 80 char TTY, (with tabs/indent set to 2, 4 or 8 spaces), to have been written by a moron.

    130. Re:One word.. by Anonymous Coward · · Score: 0

      The original is easier to understand and maintain. The problems with GOTO arise when it's used to move the instruction pointer backward instead of forward. All of the GOTOs in geode_aes_probe drive execution towards the end of the scope.

      The only change to the original that I would make would be to add a label "success:" to above line 549 for documentation purposes.

      Your proposed solution has a number of readability issues, but hands-down the one that will cause the most bugs is that you are testing negative conditions instead of positive conditions.

      The original code guards GOTOs with positive conditionals. Your proposed solution negates these conditions so that your ifs will be nested. I suggest that you read up on the following:

      http://c2.com/cgi/wiki?ArrowAntiPattern
      http://c2.com/cgi/wiki?GuardClause

      I don't write code for Linux; I'm a C# developer that uses GOTO to escape nested loops instead of littering the code with state variables.

    131. Re:One word.. by QuoteMstr · · Score: 1

      And how is that not the moral equivalent of goto?

    132. Re:One word.. by suomynonAyletamitlU · · Score: 2, Insightful

      I can understand what you mean (and your code) and that's probably how I would have written it that way too, but I have to say that the goto code is more elegant.

      Indented code is very useful when you are trying to look at logical levels, but at the same time, it makes it difficult to track the forward flow of code, especially when each step of indentation is very small. For example, in that code, you never have lines that stick out--you have the previous if(...) and then the next if(...) right below it, competing for attention, when in fact it may not even be called next if the statement equates to false. In the original code, the conditional and the code to be run are fairly distinct. You can see "This is what happens normally" and then, having that in hand, go back and track where each error goes, and then you say "Aha, they all come back to the same place, it's just that the closer you got to finishing, the more you have to undo."

      It may be personal preference but I have to say, when things line up, they're easier to understand; too many indentations per line of code is distracting.

    133. Re:One word.. by Anonymous Coward · · Score: 0

      I can't find it now, but somewhere on the joelonsoftware site he says that in Excel the height of a font was hardcoded to be 100 or something. Worked great so long as nobody changed the font.

    134. Re:One word.. by adisakp · · Score: 1

      Breaking out of a deeply-nested loop, as can happen when you’re looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.

      Actually, there is a simple work-around without a goto to the lack of a labelled break in C. Make the deeply-nested-loop search a function and "return" when you've found the element. If it's a relatively small loop, the compiler should inline it and basically generate the same code you'd get as if you had used the goto but without the goto. You can do this for just about anything although if done too often it does lead a bit to function bloat.

      I personally don't think 'goto' when used in place of a labelled-break is all that bad. It avoids the function bloat of the method above and it also runs faster in DEBUG (non-inline / non-optimized) builds.

      One place I do use 'goto' is to jump past conditional branches from within another condition where they actually perform an optimization that is impossible to recreate using standard C structures without copy-and-paste to duplicate code.

    135. Re:One word.. by binkzz · · Score: 1

      Not to be a pain, but can you give the code to your example?

      I understand your explanation, but having the code makes it easier for me to put a side by side comparison.

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    136. Re:One word.. by box4831 · · Score: 1

      Looks like a regular old OR to me.
      A B | ifpart runs?
      0 0 | no
      0 1 | yes
      1 0 | yes
      1 1 | yes

      --
      Miller Lite tastes like water that's somehow managed to rot.
    137. Re:One word.. by adisakp · · Score: 1

      The 'goto' version is very easy to understand once you get past the fact that they're essentially the same code. Once you grok the pattern, either one is easy to read. You simply need to think about it a bit more... maybe write that pattern a couple times and you'll grok it sooner or later.

      I will agree the nested version is simpler for people who don't grok the 'goto' pyramid. Also, one needs to use significantly more care coding the goto version because one can easily screw up the 'goto' version with a misplaced label or an improper goto target -- that's much harder to do with 'if' logic.

      The benefit of the goto version in readability is you don't have a ton of tabs and braces shifting your code out to the right. Basically, the code you posted here is nearly unreadable from the line wraps and indentation. If you cut and pasted the 'goto' version into your narrow slashdot post, it would be more readable for the post width. Futhermore, startup code often follows step-by-step logic unless something goes wrong (which is hopefully the very rare case) so it's easier to consider the code in a linear manner at the same indentation level and then only break the flow if something goes wrong, rather than breaking the flow (indenting a level) at every step of the code-- especially if there are a lot of steps involved in starting up the process.

    138. Re:One word.. by WinPimp2K · · Score: 1

      That is bad, but I'll raise you one further.
      Code in a limited memory space where you are not only calculating line numbers for gotos, but add in massive overlay usage to the mix. I once inherited that kind of code and had to maintain and extend it.

      Further as it was interpeted, variable names and comments sucked up precious RAM so it was all 2-3 character variable names and there were no comments.

      --

      You either believe in rational thought or you don't
    139. Re:One word.. by Requiem18th · · Score: 1

      You are not telling me VB allows line numbers in its code do you? OMG I just found a new item to my list of why VB sucks.

      --
      But... the future refused to change.
    140. Re:One word.. by brkello · · Score: 1

      If your "pyramid" is small enough it is easy-ish to read, not so much if it is a large chunk of code. I say easy-ish because it looks like awkward coding to me. If it spanned a page, it would be hard to keep track of which teardown call mapped to which if statement. It would be every easy to associate the wrong call with the wrong if statement. It would be less ambiguous and less prone for bugs with goto's.

      --
      Support a great indie game: http://www.abaddon360.com
    141. Re:One word.. by Nall-ohki · · Score: 1

      I personally find this EXTREMELY hard to read.

      Frankly speaking, nesting code that deep makes it extremely hard to read and follow. Much more so than the very clear "filter weird cases then move down the line" paradigm that the previous example uses.

      Additionally, you're moving the end of the blocks so far from their start that it's nearly impossible to remember what conditions you're in by the time you're 3 deep, and even more difficult to refactor-as-you-go which I'm constantly doing to make better code.

      Almost all of my code, with very few exceptions, is 2 indents or less.

    142. Re:One word.. by Bakkster · · Score: 1

      Sure, there are tons of reasons:
      1) Self documenting.
      2) One fewer line of code: "Exit while", rather than "goto end" and "end:"
      3) There's no guarantee that, for the line "goto end", the label "end:" will always be exactly where you expect.
      4) Too many labels (end1, end2, end42, exit1) makes large programs unsustainable and confusing.
      5a) Exit While is linked to your {}'s. If your Exit While has a problem, you know it's because your While loop's scope has an issue.
      5b) If your while loop works, and Exit While will boot you to the correct place.

      There's absolutely no reason not to let an "Exit While" do all the work for you, when a "goto" is inherently more versitile, and therefor unsafe.

      --
      Write your representatives! Repeal the 2nd Law of Thermodynamics!
    143. Re:One word.. by pete_norm · · Score: 1

      Look in particular at the "geode_ass_probe" function.

      That's why i just remember a strange pain in my back side from the last time i booted my Linux partition.

    144. Re:One word.. by Anonymous Coward · · Score: 0

      It's much easier, with gotos, to see that the function is calling a series of crypto_register_alg. That is, it's easier to see what the function's purpose is.

      With nested ifs it looks like the function's primary purpose is to evaluate a set of conditions. Yes, it does just that, but it's not the goal of th function. Otherwise wouldn't you name the function something like evaluate_errors_while_trying_to_geode_aes_probe?

      The usage of a particular language construct very often follows a pattern. Often, error handling is one of those patterns used with gotos because it can (if done right) take the focus off of processing the errors and on to what is actually intended to happen. An experienced coder will spot the pattern quickly noting that the labels are all towards the end of the function and all result in the same eventual result (the call fails).

    145. Re:One word.. by 1729 · · Score: 1

      As a programmer it scares me genuinely to see your post get rated +5 Informative. GOTOs have no place in man made code. There are so many reasons why not to use GOTOs, and only very few situations that GOTOs make for cleaner code (specifically, the usually implemented break, last and next GOTO surrogates). If one of the people in my team uses GOTOs I tell them off.

      It's good that Knuth isn't on your team:

      "By the way, if you don't like goto statements, don't read this. (And don't read any other programs that simulate multistate systems.)"

    146. Re:One word.. by clone53421 · · Score: 1

      That could be said of any control structure... and that's the whole point.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    147. Re:One word.. by Anonymous Coward · · Score: 0

      Cool story bro.

    148. Re:One word.. by shutdown+-p+now · · Score: 2, Insightful

      But why use a loop + break, when your loop isn't really a loop (i.e. it only executes once)? Every time I see this trick, it makes me cringe: it is just a goto in disguise, and its sole reason for existence is that disguise! If the given situation is best handled by goto (and there are many such cases), then don't be shy and just use it.

    149. Re:One word.. by ceoyoyo · · Score: 1

      Yeah, you know these function things? Nothing more than invisible GOTOs, which are really just gussied up jmp instructions. You shouldn't use those either.

      GOTOs are considered dangerous (not always bad, just dangerous) because you can jump to arbitrary places. Neither function calls nor exceptions, unless you go out of your way to abuse them, allow arbitrary jumps.

      His alternative to exceptions? Return an error code. Well, an exception is just returning an error object.

    150. Re:One word.. by ceoyoyo · · Score: 1

      Every goto is just a jmp plus some extra characters.

    151. Re:One word.. by shutdown+-p+now · · Score: 1

      You write side-effect free code in C (or other language that has goto)?

    152. Re:One word.. by clone53421 · · Score: 1

      I'd do this instead:


      int myfunction(const char *inFile, const char *outFile) {

        FILE *in = NULL;

        FILE *out = NULL;

        char *buf = NULL;

        stats_type *stats = NULL;

        int rc;

        rc = -1;

        if (!file_exists(outFile))

        if (NULL != (in = fopen(inFile,"r")))

        if (NULL != (out = fopen(outFile,"w")))

        if (NULL != (buf = (char*) malloc(someMagicSize)))

        if (NULL != (stats = stats_new()))

        {

          rc = 0;

          while (!rc && fread(buf, someMagicSize, sizeof(char), in) == someMagicSize) {

            stats_datum* record = stats_new_datum(buf);

            if (record != NULL) stats_store(record);

            else rc = -1;

          }

          if (ferror(in)) rc = -1;

          if (!rc) stats_print(stats, out);

        }

        if (in) fclose(in);

        if (out) fclose(out);

        if (buf) free(buf);

        if (stats) stats_free(stats);

        return rc;

      }

      For some bizarre reason it's not showing space where the blank lines should be in the preview, but hopefully they show when it submits. Anyway, the blank lines are just to make it look better anyway...

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    153. Re:One word.. by clone53421 · · Score: 1

      Jump, jump relative, etc, is all basically GOTO except that its at the machine level, and since there isn't anything else, you use it (no sparky, there is no do-until or for-do, not in assembly).

      Anonymous Coward, meet REPNZ!

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    154. Re:One word.. by clone53421 · · Score: 1

      Nay, to write an XOR you'd have to test (a && !b) in the first condition. It'll always execute if (a) evaluates to true, regardless of the value of b.

      The other guy said the same thing, but he didn't explain it, so I tried.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    155. Re:One word.. by clone53421 · · Score: 1

      Guns don't kill and GOTOs don't make bad code, people do.

      Ah. Good point. Handing GOTO to a lousy coder is like saying "You know, you couldn't hit the broad side of a barn with that gun, try this rocket launcher instead."

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    156. Re:One word.. by davidbk1 · · Score: 1

      Yes, it's not. If A and B are true the if succeeds. Also, if B is not changed by the IfPart, you have an infinite loop if A is false and B is true.

    157. Re:One word.. by snadrus · · Score: 0

      int done = FALSE;
      int x = 0, y = 0;
      int target = WHATEVER;
      int multiArray[100][100];
      init(&multiArray);

      do{
      do{
         if (multiArray[x][y] == needle)
           done=TRUE;
      }while (!done && y++ < 100);
      }while (!done && x++ < 100);

       

      --
      Science & open-source build trust from peer review. Learn systems you can trust.
    158. Re:One word.. by GWBasic · · Score: 1

      Have you ever tried abusing the try/catch statements?

      That's even worse. Throwing an exception is a resource-intense operation; and many debuggers have a break-on-exception feature. As a result, it's a pain to debug mysterious exceptions because the program will keep breaking into the debugger where someone used try/catch instead of normal logic.

    159. Re:One word.. by sjames · · Score: 1

      GOTO is actually a decent way to handle error conditions in a function where you need to unwind. In the end, it makes the code much more readable and so prevents missing important things like freeing a malloc:

      err=ENOMEM;
      a = malloc(some_size)
      if(!a) goto out;
      ... stuff...
      b = malloc(other_size);
      if(!b) goto out_free;
      ...stuff...
      out_free: free(a);
      out: return err;

      If there are many steps and resources that must be allocated and freed (or locks to take in order for example) you can either obfuscate the actual code in a deeply nested set of conditionals (not to mention copy/pasting the cleanups) or you can neatly unwind and return an error using goto.

    160. Re:One word.. by benhattman · · Score: 1

      Ever hear of writing functions for that?

      E.g.

      Foo* findFoo(string& name) { // deeply nested loops!!!!
          {
              {
                  {
                      {
                          return result;
                      }
                  }
              }
          }
          return NULL;
      }

      Your example is exactly why goto is considered harmful. Most of the time when people think it's necessary, they just haven't decomposed their problem correctly.

    161. Re:One word.. by Alpha830RulZ · · Score: 2, Insightful

      I did years of work in Business Basic, and we managed to generally avoid go-to's even back then. Plenty of gosubs, but we tried to avoid the goto's.

      I have managed to avoid using a single goto since then. It's been 21 years, and at least half a dozen languages. I don't even recall being tempted or wishing I could.

      --
      I was taught to respect my elders. The trouble is, it's getting harder and harder to find some.
    162. Re:One word.. by aquila.solo · · Score: 1

      Okay, I see that now. That should teach me to not try logic analysis at 0400.

      And thanks to the other posters below who also corrected me.

    163. Re:One word.. by Anonymous Coward · · Score: 0

      Such loops are almost certainly buggy

      [citation needed]

      That seems a bit redundant. You just cited him, didn't you? I get the strangest feeling of recursion when someone quotes somebody else and asks for a citation...

      citation, please

    164. Re:One word.. by amRadioHed · · Score: 1

      Sure, but clearing a frozen logjam has nothing to do with sculpting ice with a chainsaw.

      --
      We hope your rules and wisdom choke you / Now we are one in everlasting peace
    165. Re:One word.. by clone53421 · · Score: 1

      How do you get an infinite loop? The execution skips past the else clause.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    166. Re:One word.. by BenoitRen · · Score: 1

      How about 2-character indentation, then? That's my preference. 4-character indentation is already too wide for my tastes.

    167. Re:One word.. by sjames · · Score: 1

      Arguably, the only difference from break label and goto label is that break label further obfuscates what line is executed next. Otherwise, it parses down to exactly the same thing.

      Point 2 is quite true though arguably a return in mid structure is also semantically similar to a goto.

      The primary reason "GOTO considered harmful" is not that it is intrinsically bad, but because too many coders used them mindlessly to create a big jumbled mass of spaghetti.

    168. Re:One word.. by KDR_11k · · Score: 1

      I thought those set their text displays up to use something like 200 columns to make the most of their screen.

      --
      Justice is the sheep getting arrested while an impartial judge declares the vote void.
    169. Re:One word.. by skarphace · · Score: 1, Insightful

      Almost all of my code, with very few exceptions, is 2 indents or less.

      Man, to me, it feels like you guys are stuck in the past. I'd like to think most of us have moved away from vi and are using a modern IDE, or at least a graphical text editor. Horizontal scroll is not the devil, guys.

      --
      Bullish Machine Tzar
    170. Re:One word.. by dkf · · Score: 1

      GOTO :-) (or is that two..?)

      It's a primitive flow control construct. Like all primitives, it's best avoided when something else higher-level will do the job just as well, but when you've got nothing else that will do a neat job, it's better than bodging it with something else (e.g., replacing gotos with a mess of flag variables isn't usually an improvement as control logic - even gotos - is usually easier to read than complex expressions). But only languages that don't let you create your own control constructs need something as low-level as a raw goto.

      Computed gotos are evil. If you ever need one, feel dirty.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    171. Re:One word.. by hairyfeet · · Score: 2, Interesting

      Don't I know it. Mike was a blast to have as a teacher. He was a former Navy man who coded for DoD in the 80s and got burnt. One of the funniest part was at the beginning of a class he would whip off some chunk of code that would explain what he was doing that day and it would NEVER work. He would then project it on the board, and then after finding out what class he was teaching ATM, like say VB, he would go

      "okay...this is C++, that isn't gonna work there /replaces with VB code/ and that is Java, which I taught last class /replaces with VB code/" and after a couple minutes of this talking to himself and replacing code it would work beautifully. He just knew so many languages and taught so many classes he would get a little "off" at the very first of the class and need a minute to get his groove back. He was a great teacher and really stressed understanding exactly what the code was doing step by step. He said if you understood what the code was actually doing, instead of just learning to regurgitate the language, then your code should be easy to maintain. He also stressed good commenting so that those that come after you could see how your logic flowed on a particular implementation, and could easily pick up where you left off.

      He was a real blast, and could give you a lengthy conversation on just about any language ever written. It was great having a teacher that knew so much about coding and could really push you to learn and do more. I may be a PC repairman and thus rarely get to code anything, but his method of working the process to hunt down bugs by always working at the simplest level (which he demonstrated by having one of the kids who thought he was a "network wizard" try to diagnose a problem with a desktop. Turned out Mike had unplugged the network cable and the kid never thought to check because he was too busy doing ping, checking services, etc) I still use to this day to work my way through an irritating bug. Just a great teacher.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    172. Re:One word.. by dkf · · Score: 1

      Code in a limited memory space where you are not only calculating line numbers for gotos, but add in massive overlay usage to the mix.

      Oh, overlays. I've been trying for 15 years to forget them. Thanks a bunch for bringing the nightmares back.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    173. Re:One word.. by Anonymous Coward · · Score: 0

      There is an almost religious fervor against goto, I admit.

      The problem with it is that it is also very often a dirty hack used to fix badly written algorithms. In other situations such kernel programming, for instance, it is simply the best solution available for some tasks. New programmers should be steered away from goto to keep from forming bad habits in higher-level languages.

      It depends on the paradigm you are using. In procedural programming like C device drivers and kernels use goto statements! But as you use higher level programming languages goto is less useful and more of a dirty hack.

      I think the religious war against goto started from Dijkstra's "GOTO Statement Considered Harmful" which is still worth a read.

    174. Re:One word.. by 1729 · · Score: 1

      Have you counted the number of GOTOs in the linux kernel?


      % cd linux-2.6.30.5
      % grep -r goto . | wc -l
            66983

    175. Re:One word.. by EvilBudMan · · Score: 1

      There is probably a lot of old FORTRAN code still be used where line numbers were a requirement. By god I really hate FORTRAN for some reason. I don't much like a bunch of nested if code either, so what you are saying makes sense to at least limit the width of the nesting to the size of your monitor or something. 100 columns is OK. 180 or greater is bad bad. Of course there is and will continue to be all kinds of ways people get used to doing things.

    176. Re:One word.. by Sir_Lewk · · Score: 1

      I swear by Vim and use 8 space indents, I don't see what vi/vim has to do with using small indents, unless you are foolishly assuming that vi/vim users only use 80x24 terminals (275x73 is what I usually use, a fullscreened xterm. any larger and the text would be too small to see) Granted, I often have multiple windows in vim opened up, tiled so I can look at multiple pieces of code at once, but even then I never have an issue with 8 space indents.

      Furthermore, vim can optionally either wrap lines around, or do horizontal scrolling...

      --
      "linux is just DOS with a UNIX like syntax" -- Galactic Dominator (944134)
    177. Re:One word.. by K.+S.+Kyosuke · · Score: 1

      I really like what Guy Steele Jr. wrote about this in Lambda: The Ultimate Goto:

      One can argue quite strongly that there are so large a number (possibly infinite) of distinct useful control constructs that no one language could embody them all, and that therefore no language designer should be so conceited as to think he has encompassed all desirable constructions in a given language. By this reasoning, the omission of CASE, or Dahl loops, or event constructions, or whatever else is not a matter of neglect, but of necessity: you just cannot foresee them all.

      ...

      Until a much more advanced theory of programming is devised, designers of practical languages are well advised to leave in "ugly hooks" like GOTO, even if also discouraging their use except in emergencies. After all, using GOTO to simulate a peculiar control construct is probably preferable to a convoluted perversion of a more specialized construct.

      .

      --
      Ezekiel 23:20
    178. Re:One word.. by Follis · · Score: 1

      Try editing C or C++ in VI or emacs. Very fast, very efficient, and horizontal scroll _is_ the devil. Even the web 2.0 people think so. Ben

    179. Re:One word.. by sjames · · Score: 1

      Unlike the normal linux convention where one can quickly find all function return conditions while looking at the bottom, yours is hidden away in the middle of a big nest. That is no less of a style violation than goto (effectively it IS a goto). It just doesn't have a famous paper written about it.

      There is plenty of room to argue which is the greater sin or that they are merely symbolic transformations yielding 2 exactly equivalent ways of doing it.

    180. Re:One word.. by volpe · · Score: 1

      Here's my example. Just wrote this yesterday. First time I used a go-to in years:

      // Wait for the creator to create the named pipe and start
      // accepting connections
          BOOL waitSucceeded = false;
       
      // Wow, this is the first time I've used a goto in years. Similar
      // in spirit to Duff's Device, but not as gross looking.
          goto FIRST_ITERATION;
          while (! waitSucceeded)
          {
              Sleep(50);
      FIRST_ITERATION:
              waitSucceeded = WaitNamedPipe(fullname,NMPWAIT_WAIT_FOREVER);
          }

      This code loops until a server process is ready to communicate over a named pipe. If it's ready at the time this code is executed, it proceeds with no delay. If the server hasn't issued a ConnectNamedPipe yet, it blocks. But if the server hasn't even *created* the named pipe yet, the wait function returns immediately, despite the "wait forever" flag, and we need to loop. Alternative approaches include (1) code the "wait" call twice, once inside the loop and once before the loop, and conditionally skip over the loop, and (2) make the loop an infinite loop with a conditional break inside. I don't like the former because it's superfluous code duplication. I don't like the latter because, logically, if a loop has one termination condition, it should occur inside the test expression of the "while" statement. An infinite loop with a conditional break is a kluge.

    181. Re:One word.. by Anonymous Coward · · Score: 0

      So, where's your example?

      Here's a project you may have heard about.

    182. Re:One word.. by RackinFrackin · · Score: 1

      Here's an example. I wrote a program that did a brute-force search for partition of a set into special subsets. Each element of the set was indexed by a 5-tuple, so the program used five for loops to iterate over the 5-tuples. Each time it found a 5-tuple that was compatible with the working partition, it adds it to the partition and continues searching forward from there.

      Each time the search reached a dead end, it would have to back up. Backing up involved tossing the last subset that was added to the working partition and resetting the five variables to match the next 5-tuple after the one that was tossed. The easiest way to do this was to manually reset the five variables and then jump back into the middle of the nested loops by using a goto statement.

    183. Re:One word.. by Flodis · · Score: 1

      Ugh. Magic invisible gotos FTW!

      Say what? The linked article proposes using return values (that will be ignored) instead of exceptions. If you wanted to discredit the use of try/catch, you need to find a better link.

      (Or is the article supposed to be ironic? It looks genuine. If not, a big whoosh on me...)

    184. Re:One word.. by chgros · · Score: 1

      > If you're breaking out of a loop, you should use 'break'. If you're continuing a loop, 'continue'.
      What if you're breaking out of / continuing an outer loop?
      e.g. (pseudocode)

      foreach(i) {
            foreach (i->j) {
                  if(failtest(j)) { // continue outer loop
                        goto nexti;
                  }
            }
            foo(i);
            nexti:;
      }

      I often use this. I like it better than adding a boolean flag. I think it's actually clearer that way.
      Admittedly the inner loop could be made into a function, but if it relies on a lot of context, that's pretty painful.

    185. Re:One word.. by julesh · · Score: 1

      You often cannot develop software with the language you want, but must develop it with the language you have. C has no such features and, therefore, goto is used more often than in languages that have them. Fit the strategy to the tool.

      Yes, but tools are chosen for the variety of strategies they offer. Usage of C has been in constant decline for over 10 years now, and it is rapidly becoming a minority language, at least in fields outside of systems and embedded software.

      Admittedly, C++ also has this shortcoming.

      And, no, exceptions are not part of C

      Fortunately, it doesn't have this one.

    186. Re:One word.. by Anonymous Coward · · Score: 0

      You people are insanse. Use c++ and stl. Problem solved.

      And please don't come crying to me about 'bloat', or 'speed'. std::vector is exactly as fast as a C array if your optimiser was written after 1980.

      If your array is fixed size, use boost::array instead. Same syntax & semantics, works with standard algorithms, exactly as fast as fixed-size C array.

    187. Re:One word.. by julesh · · Score: 2, Insightful

      Finite State Machines. They really are quite difficult to implement without goto logic


      int state = BEGIN_STATE;
      while (state != EXIT_STATE)
      {
          switch (state)
          { ...
              case SOME_STATE_OR_OTHER: ... do something ...
                  state = NEXT_STATE;
                  break; ...
          }
      }

      I fail to see the problem. Or there are table driven solutions that are much more amenable to automatic code generation.

    188. Re:One word.. by Nicolay77 · · Score: 1

      I don't think beginners have been using goto in the last 10 or even 15 years.

      --
      We are Turing O-Machines. The Oracle is out there.
    189. Re:One word.. by SL+Baur · · Score: 1

      To me, nested ifs are much easier to read - they convey the meaning/intent of the code a lot better. As in 'if this function call works, then do this. Otherwise, just clean up and exit'

      Besides the excessive indentation, my mind starts to swim in a wall of close braces. More than something like 2 levels of nested ifs is hard to read, in my opinion. Indeed, I find the original version easier to read, though I would remove the assignments in the conditionals.

      It probably doesn't matter in a probe routine, but in code that has a really hot path the separation of slow path, error handling code causes less icache line pollution in the hot path, thus maximizing performance in the normal case.

    190. Re:One word.. by SL+Baur · · Score: 1

      +1

      It's not. But nor is code that uses goto in the idiom that FourthAge posted above.

      My objection to that code is that if you do even just three or four allocations, you start getting very large indentations pretty fast, especially if you like 8-character indentations [sourceforge.jp]. (They get pretty long even with 4, which is what I like!) This causes a problem if you restrict yourself to 80-columns [sourceforge.jp].

      Arguably this is a problem with restricting yourself to 80 columns,

      For me, these are the main reasons I love having both of those restrictions. It forces one to keep nested ifs to a minimum, the bane of testing and reading comprehension.

      Now it is time for a language designer to step up to the plate. We know what kind of control structure we want - code that compiles into something as icache friendly as the geode driver. It's not going to be exceptions. Even with exception support in Ada, it was still deemed necessary to have goto. Exceptions are fairly heavy weight since potentially stack frame unwinding must done (which implies additional runtime code when only a simple goto is needed).

    191. Re:One word.. by SL+Baur · · Score: 1

      And so on ... it basically gets you exception handling formatted code. Of course, goto is probably still cleaner :)

      Yeah. Where is execution intended to go after the if() at the bottom of the while() fails? I also fail to see how unwinding occurs.

      Personally, I find free variables a lot more irritating than an occasional goto, even if the goto is not very well thought out.

    192. Re:One word.. by pbaer · · Score: 1

      break(3); or however deep you are in the loop.

      --
      There are 11 types of people, those who know unary and those who don't.
    193. Re:One word.. by SL+Baur · · Score: 1

      wouldn't a switch be just as easy? just leave out the break in each section and it'll flow through everything below it

      The semantics on switch are not correct. Think of it as a computed goto.

      Now if you had a dynamic switch, with the cases computed bottom to top, you would have the correct semantics.


      reverseswitch {
      case ret = initialize4(): /* executed fourth */
              unwind4(); /* and fall through */
      case ret = initialize3(); /* executed third */
              unwind3(); /* and fall through */
      case ret = initialize2(); /* executed second */
              unwind2(); /* and fall through */
      case ret = initialize1(); /* executed first */
              unwind1();
              return ret;
      } /* further processing, we know we initialized */

      Now, if the individual cases are evaluated bottom to top (oops, just violated the top to bottom rule), then that would give the correct semantics.

      So now, we have mixed orders of execution, bottom up in the case of the evaluation of the different cases and top down in the case of the error unwind. Which is exactly what we want. Is this any easier to read than the gotos?

      I suppose we could count on the compiler to separate out the unwind logic. We want the machine to execute the equivalent code with gotos, not necessarily have to look at it.

    194. Re:One word.. by Kittenman · · Score: 1

      Disagree. If goto is the best solution to the problem, then you're not looking at the right problem.

      --
      "The greatest lesson in life is to know that even fools are right sometimes" - Winston Churchill
    195. Re:One word.. by SL+Baur · · Score: 1

      If you regard language features as âjustâ(TM) syntactic sugar, why arenâ(TM)t you programming in raw machine code?

      If-then-else, do-while, for, etc. are syntactic sugar. They can all be rewritten fairly cleanly with gotos. See http://www.amazon.com/Elements-Programming-Style-Brian-Kernighan/dp/0070342075

      The issue has always been unstructured use of goto. The difference is that with a formal control structure you have strict rules as to when there is a goto (as to the else clause). With a goto you have to read a bit harder to see what is happening because it's usage is not guaranteed to be structured.

      They called it Structured Programming for a reason, but it's still syntactic sugar.

    196. Re:One word.. by SL+Baur · · Score: 1

      As long as the gotos only go down, i.e. like a return or break, there is no spaghetti code.

      The Ada guys seem to agree with you on that. Break, but no continue. I don't personally have any issues with continue. In code that's a spaghetti of deeply nested if-then-elses mixed with loops, it can be somewhat difficult to see where they go to next, but the same can be said of break too.

    197. Re:One word.. by SL+Baur · · Score: 1

      No need for goto, though occasionally it comes in handy.

      Congratulations. You have just implemented goto with a variable assignment. How is that any more readable than a plain goto?

      If that switch statement is of any size, you will be forced to check the code after it before going to the next state when manually tracing execution. It's not any cleaner than straight gotos and arguably worse (extra levels of indentation). Now if there is actually code that needs to be done in between state transitions, then you're better off.

      The key is not that all uses of goto are harmful. The key is "if I use goto, is my code more or less fragile when the next guy comes along to maintain it?" Fragile code is guaranteed to be broken and often times, obeying top to bottom, no multiple exit points, no break or continue, multiple flag variables to track state and deeply nested if-then-elses is the most fragile code of all if it needs to be modified. I believe I'll write a journal entry about that. Hello Ron Louie if you're reading this.

    198. Re:One word.. by SL+Baur · · Score: 1

      Many modern languages don't support GOTO, or only include it to support machine generated code (ADA).

      Ada is not an acronym. And Ada supports goto because it is a low level systems programming language and kernel code that separates fast path usual case code with error handling slow path code is less error prone and faster.

      As you can tell from that, and many other sides, there are no major pros to using GOTOs, but very major negatives.

      Um, did you even bother to read that link? He's basically arguing from the same position I am and against dogmatic wankers like you appear to be.

      In the remaining one case out of 100 in which a goto is a legitimate solution to the problem, document it clearly and use it.

      Seems like a fair statement. Compare that to

      GOTOs have no place in man made code.

      There's been little argument that most gotos can be replaced with equivalent and convoluted "structured" code. One of my favorite languages (Icon) does not have goto. It has a rich set of control structures that permit you to do pretty much what you need to do. Its functional domain does not require the use case of whittling clock cycles off of interrupt handlers.

    199. Re:One word.. by EvanED · · Score: 2, Insightful

      It forces one to keep nested ifs to a minimum, the bane of testing and reading comprehension.

      My biggest problem with 80-character limits is that if you have reasonably descriptive identifiers, they tend to be a little long, and so it's not all that hard to go beyond 80-characters even if you are only a couple levels deep in code. If you're in a language with function definitions inside of a class like Java or Python, you've already got two levels of indent to your function body before you've even started writing actual code! With 8 character indents, that's 20% of your line width already gone. If you have an if statement in two nested for loops (not at all unreasonable), that's 5 indent levels and half of your line width! If you then make a function call with two parameters, save the return value, and your average variable length is 8 characters, you're at 80 characters; and that's not even that long of a line, even for someone like me who likes to use a lot of explicit temporaries.

      The other thing is I tend to view line breaks as having a pretty high cost, especially if there are a couple related lines in a row. If you are doing similar operations two or three times in a row, it's nice to see the parallel structure, and adding line breaks obscures that quite a bit. (I used to try to line up operators in such cases, but I rarely do that any more. :-))

    200. Re:One word.. by Anonymous Coward · · Score: 0

      or you can throw some exception and have a cache block outsize the loop

      in some language, using exception like this is also useful to get out of deeply recursive calls, but be careful because in many languages implementation of exception is slower than just simple return from the functions.

    201. Re:One word.. by SL+Baur · · Score: 1

      Show me your code and I'll show you an alternative.

      So what? I guarantee that whatever you come up with will be slower, less readable and hence more expensive to maintain.

      Kernel code is the perfect application domain at this time for use of goto for slow path error clean up. And see the example of a proposed structured construct with identical semantics that requires both bottom-to-top and top-to-bottom semantics that I posted earlier.

    202. Re:One word.. by SL+Baur · · Score: 1

      Please see above my example. Sometimes not to use goto is impossible if you also want to avoid duplication of the code.

      Hear! Hear! Document it in the comments. You're fine.

      Repeated code is *a lot* more of a maintenance nightmare than a few gotos.

    203. Re:One word.. by Anonymous Coward · · Score: 0

      > It doesnâ(TM)t matter what the compiler does; source code is for humans.

      Source code is for compilers. English is for humans.

      Mi parolas Esperanton, vin malsimpatian bulon!

    204. Re:One word.. by Anonymous Coward · · Score: 0

      If you reformat your code to use 8-character indentations ... your code would become a bit uglier

      that is all you needed to say really. 2 character tabs are standard most places, 4 character tabs is a waste of space IMO, 8 characters tabs is just plain stupid, I dont give a shit what linus says.

    205. Re:One word.. by Anonymous Coward · · Score: 0

      And is this code any less readable?

      Foo* findFoo(string& name)
      { // deeply nested loops!!!!
            Foo * pResult = NULL;
              {
                      {
                              {
                                      {
                                              pResult =
                                              goto SearchDone;
                                      }
                              }
                      }
              }

      SearchDone:
              return pResult;
      }

    206. Re:One word.. by Anonymous Coward · · Score: 0

      that story was gay

    207. Re:One word.. by binkzz · · Score: 1

      Why resort to namecalling? You had a perfectly good intelligent post otherwise.

      --
      'For we walk by faith, not by sight.' II Corinthians 5:7
    208. Re:One word.. by Anonymous Coward · · Score: 0

      Nested IF within nested comments on 9 inch screen is FTL.

    209. Re:One word.. by wilx · · Score: 1

      You make no sense. You have been brainwashed. Please, stop repeating what you have been told in school without thinking about it. Read Dijkstra's "Go To Statement Considered Harmful" essay and think about what he says there. Then read the "Go To Statement Considered Harmful:
      A Retrospective" essay and think again.

    210. Re:One word.. by Aladrin · · Score: 1

      If your language supports it, you can break multiple loops at once.

      In your example above, though, a 'break' instead of your 'goto nexti' would do exactly the same thing. The foo(i) would not get executed in either case, and the outer for(i) loop would continue at the next value.

      I think you mean to place the foo(i) and nexti: after the last brace, though.

      I would rather just use a boolean flag, and name it properly. It would be easier to read.

      --
      "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    211. Re:One word.. by clone53421 · · Score: 1

      (3) in the while:

      waitSucceeded = WaitNamedPipe(fullname,NMPWAIT_WAIT_FOREVER);
      if (! waitSucceeded) Sleep(50);

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    212. Re:One word.. by clone53421 · · Score: 1

      GP meant exactly what he said, but I'd say it's much clearer with the boolean flag. (You were confused.)

      bool skip;
      foreach(i) {
        skip = FALSE;
        foreach (i->j) {
          if(failtest(j)) { // continue outer loop
            skip = TRUE;
          }
        }
        if (!skip) foo(i);
      }

      E.g. let's suppose i is an array of groceries, and their subproperties j are their ingredients. You're allergic to dairy. If any ingredient i->j is a dairy product (failtest), you skip that i. Otherwise, you buy it (foo).

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    213. Re:One word.. by clone53421 · · Score: 1

      Whoops, forgot to break in my inner loop.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    214. Re:One word.. by matmota · · Score: 1

      You might prefer to use do...while instead, to avoid the chance of unintended looping:

      do
      {
                      if (!start_condition) break;
                      action1();
                      cleanup1();
                      if (!test_condition1) break;
                      action2();
                      cleanup2();
                      if (!test_condition2) break;
      } while(0);

    215. Re:One word.. by chgros · · Score: 1

      GP meant exactly what he said, but I'd say it's much clearer with the boolean flag
      Let's agree to disagree ;). Also, using a goto is more efficient, unless the compiler is smart enough to get rid of the boolean flag (which I'm not sure it is in general)
      You were confused
      How so?

    216. Re:One word.. by coolsnowmen · · Score: 1

      Column width on a display never bothers me because of wide-screen, high resolution and scrolling.

      Column width when printing using mono-spaced fonts on the other hand, can make or break readable code.

    217. Re:One word.. by coolsnowmen · · Score: 1

      My biggest problem with that use/abuse of the switch statement is that it is easy to miss the 'cleverness' of it. That is, I try to write code that someone else can understand (or comment it to explain), and people are not used to one case stacking burger-time style. So it will be confusing.

    218. Re:One word.. by coolsnowmen · · Score: 1

      You can cleverly implement a finite state machine as a matrix. Use the first index into the matrix as the current_state, and the remaining indices as the input. The value that maps to is the next state. If you need output, make it a struct with next state and output.

      I learned that from a FSM teacher, and it seemed like he'd used it before.

    219. Re:One word.. by clone53421 · · Score: 1

      You [Aladrin] were confused
      How so?

      Read what he said again. He clearly didn't understand what your code did. As you wrote it, replacing the goto with a break wouldn't prevent foo(i) from executing (as he thought it would).

      I think he thought you meant this: (...then again, maybe he thought foo(i) and nexti: go at the very end, since he said they go after the last brace, and I'm not sure whether "last" meant "last" or "previous". However, if you put them at the end, goto nexti and break don't do the same thing – which he claimed they should.)

      foreach(i) {
        foreach (i->j) {
          if(failtest(j)) { // continue outer loop
            goto nexti; //break; would do the same thing
          }
          foo(i); //if these lines go here
          nexti:;
        }
      }

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    220. Re:One word.. by clone53421 · · Score: 1

      In any event, he said that replacing your goto with break would be exactly the same, which is incorrect. Thus, he was clearly confused by your code. I suggest that my code is far less likely to be misunderstood as yours was: For each i, if any i->j fails, skip, otherwise, do foo(i).

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    221. Re:One word.. by SL+Baur · · Score: 1

      Why resort to namecalling?

      Yeah, I felt ashamed about that. I offer my humble apologies.

      There's been too much name calling on both sides. Dijkstra's original comment regarding programmers who had not been taught structured languages from the start still burns me ...

      Again, my humble apologies.

    222. Re:One word.. by hairyfeet · · Score: 1

      Yep! I never tried to PEEK and POKE but most of my old Commodore tricks like GOTO worked just fine in VB6. Hell I could have probably broken out my old Commodore code and run it without much tweaking at all. I honestly didn't think that 20+ year old shit would still work, but i say "eh, what could it hurt to try?" and amazingly i still remembered those old BASIC tricks from the sleepless nights i spent pounding code out of the backs of mags and tweaking it to work on my old VIC. Remember William Shatner and his TJ Hooker hairpiece selling the VIC20? Ahh, those were the days. I sure as hell don't miss that damned cassette drive though. That was one royal PITA.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    223. Re:One word.. by Anonymous Coward · · Score: 0

      I understand if 20yo code could still run in, say, an emulator or compatibility layer, not directly, I hope at least VB.NET doesn't do that...

    224. Re:One word.. by CarpetShark · · Score: 1

      A decent editor like Kate will indent stuff like this neatly, without wrapping lines back to the start of the screen. It is available within IDEs, too.

      More importantly, if your function is THAT big, it should be broken into separate functions. Big functions == bad code.

    225. Re:One word.. by Adovid · · Score: 1

      You say Dijkstra was wrong. The guy made a simple comment and it changed the way we look at how we make our computer languages today.

    226. Re:One word.. by Glabrezu · · Score: 1

      After reading a thread about why C++ wasn't used for developing git (basically, apparently it's used by bad programmers), I decided to take a look at git source code, first file I check and I find this:
      http://gitorious.org/git/mainline/blobs/master/commit.c#line144
      I suppose that one wasn't written by Linus, otherwise I would tend to say that even wiz programmers tend to misuse goto :P.

      --
      Santiago
    227. Re:One word.. by kelnos · · Score: 1

      While the goto in this case does usually end up resulting in an "only one return" (or two, depending on how it's implemented), the purpose of it is to avoid copy and paste for a lot of cleanup code.  Without goto, if you do multiple returns, you end up with something like:

      if(do_something(bar)) {
          free_bar(bar);
          return -1;
      }

      if(do_something_else(bar)) {
          free_bar(bar);
          return -1;
      }

      If you have more than just one thing to clean up, or different things depending on how far you made it into the function before encountering an error, it gets worse.  And if you later add code to the middle of the function that *also* needs cleanup code on errors, then you end up copy and pasting the existing error code, and then adding an extra cleanup line to all the extra error conditions below it.

      With a simple goto on error, you can put all of your cleanup code in one place in the function, and only have a single copy of it.  Not only does this make it clearer what the code above it does (the error handling, while necessary, only serves to obscure the real purpose of the code), but it's a lot more maintainable and easier to extend.

      You could also achieve something similar with a series of nested if statements, such as:

      if(do_something(bar) == 0) {
          if(do_something_else(bar) == 0) {
              /* keep going... */
          }
      }

      ... with the error handling code after each if block, but that quickly becomes unwieldy if you have more than 5 or so operations, as you end up 6 or more indentation levels deep. I use 4-space indentation, but I know people who like 8, which makes the problem occur twice as fast.  Even ignoring the indentation issues, personally I find the "if pyramid" less readable than goto-based error handling.

      --
      Xfce: Lighter than some, heavier than others. Just right.
    228. Re:One word.. by kelnos · · Score: 1

      Heh, I assume you mean "while(0)" ...

      --
      Xfce: Lighter than some, heavier than others. Just right.
    229. Re:One word.. by kelnos · · Score: 1

      How is this so hard to understand

      It's not hard to understand, I just don't read code that way. Error handling is not a part of "what the function does." Error handling deals with exceptional conditions that you usually hope/assume won't happen, but of course the error handling needs to be there to catch the 0.2% of the time when they do.

      So "what the function does" is all the statements that have nothing to do with error handling. In the "correct" case, the function is linear: in most cases you will just execute from top to bottom, and it's done. Reading someone else's code, it'll be clearer to me much faster what is going on without the nested "if pyramid" mess.

      But hey, dif'rent strokes for dif'rent folks. That's why everyone has their own coding style.

      --
      Xfce: Lighter than some, heavier than others. Just right.
    230. Re:One word.. by volpe · · Score: 1

      In other words, perform the same test twice in rapid succession. No thanks. I like my approach better.

    231. Re:One word.. by clone53421 · · Score: 1

      I'd imagine a good compiler should be able to optimize that.

      TST waitSucceeded
      JZ exitLoop
      MOV AX, 50
      PUSH AX
      CALL Sleep
      JMP beginLoop
      exitLoop:

      The JMP "should" be a JNZ at the very end, right after a second TST ... but then you'd have a TST, JZ, TST, JNZ on the same value. The compiler ought to recognize that this can be optimized.

      In any event, if you're going to make a customized looping construct with a goto anyway, why not just go all the way and do this... it even saves you a jump:

      LOOP: {
        waitSucceeded = WaitNamedPipe(fullname,NMPWAIT_WAIT_FOREVER);
        if (!waitSucceeded) {
          Sleep(50);
          goto LOOP;
        }
      }

      And, for this particular instance, I don't see why you can't just do this instead:

      while (WaitNamedPipe(fullname,NMPWAIT_WAIT_FOREVER)) {
        Sleep(50);
      }

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    232. Re:One word.. by clone53421 · · Score: 1

      I should have had !WaitNamedPipe in my last example, but I suppose you knew that...

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    233. Re:One word.. by Optimus6128 · · Score: 1

      I had to make bad excessive use of goto since my first qbasic demo ten years ago :)

      There are few occasions though where it's the thing to do and one line of it doesn't make the code ugly. Yes, my old qbasic code was horrible (not only because of goto) but few good uses of it doesn't hurt. I find it stupid whenever I see other programmers cringe with the single mention of goto. First they should think if the case of the code where it's used justified it and then think twice about blindly disagreeing.

      In an old demo I did for the GP32 handheld there was a smooth juhlia fractal effect I coded (with fixed point arithmetic, mirroring and all that) and I unrolled the loops to gain some more (some would say loop unrolling is senseless but on that hand held there was enough gain to justify). I specifically unrolled the sixteen iteration loops of the fractal algorithm where specific conditions might make it escape abruptly from the loop with a single break. If you unrolled those loop then the only think you could use to escape had to be a goto in the line right after the end of the unrolled loops. Of course someone who hated ugly stuff like loop unrolling and taboo things like goto could just avoid this method at all but I was just writting a demo and I wanted performance.

      This is the only case in my code that I had to use a goto (and found it a good and fast solution actually).

      --
      The "H-Word" has died for me.
    234. Re:One word.. by Optimus6128 · · Score: 1

      "If you unrolled those loop then the only think you could use to escape had to be a goto in the line right after the end of the unrolled loops"

      Sorry, I made a serious mistake here:
      Should be ..use to escape had to be a goto (many actually, one for each unrolled line) TO the line right after the end of the unrolled loops"

      --
      The "H-Word" has died for me.
    235. Re:One word.. by volpe · · Score: 1

      I'd imagine a good compiler should be able to optimize that.

      Perhaps, but my objection was based more on style than on performance. The code *says* the test is being done twice, even if it isn't under the hood.

      In any event, if you're going to make a customized looping construct with a goto anyway, why not just go all the way and do this... it even saves you a jump: [code deleted]

      Why do you assume that just because I think that a goto is sometimes a nice solution, I must therefore think that a goto is always preferable? Clearly, that example is exactly the reason why the "while" loop exists in the first place. And it doesn't save a jump. There's a hidden jump in the implementation of the "if".

      And, for this particular instance, I don't see why you can't just do this instead: [code deleted]

      Yeah, that's actually nice. However, I've developed a habit over the years of trying not to put lots of "stuff" in the while-loop test. With the exception of certain well-established idioms, I find it improves readability to keep long expressions or things with lots of side effects out of the test itself. Matter of personal taste, I suppose. In this case, I could go either way, but I went with my way out of my aforementioned habit.

    236. Re:One word.. by mhelander · · Score: 1

      But as soon as that happens, it is time to break out that stuff into a new method, right?

    237. Re:One word.. by alexo · · Score: 1

      The goto statement is very useful. Your dislike of it is irrational. Do you even know why you do not like it? Often, goto is the best solution to given problem.

      GOTO is for wimps!

    238. Re:One word.. by Anonymous Coward · · Score: 0

      The alternative involves using lambdas and continuations which any modern language supports natively and with clear easy to read syntax.

  3. Ol' Slashy by Tablizer · · Score: 1, Funny

    Slashdot added a fudge th at mad e tex t h a ve ext ra sp ace s. Ho pe no bo dy foun d i t.

    1. Re:Ol' Slashy by Adm.Wiggin · · Score: 1

      There was one that gave us "Anonymous Cowardon" for a while, but that was mostly a CSS problem.

  4. pretty much everytime I write in by buswolley · · Score: 2, Insightful

    VBA

    --

    A Good Troll is better than a Bad Human.

  5. Balancing act by Tubal-Cain · · Score: 4, Interesting

    If you have short deadlines, you end up with issues similar to the bugs Ubuntu needs to smooth out every release. If you go with "It'll be finished when it is finished", Your stable releases can become ridiculously out of date between versions. Debian did a good thing by abandoning the open-ended release cycle in favor of the extremely long but predictable two-year deadlines.

    1. Re:Balancing act by moon3 · · Score: 1

      predictable two-year deadlines

      only in the world of open source..

    2. Re:Balancing act by Anonymous Coward · · Score: 0

      Debian will freeze (or "enter beta" as others would call it) on a regular schedule, but releases will come whenever they are ready, as before.

    3. Re:Balancing act by dnaumov · · Score: 1

      If you have short deadlines, you end up with issues similar to the bugs Ubuntu needs to smooth out every release. If you go with "It'll be finished when it is finished", Your stable releases can become ridiculously out of date between versions. Debian did a good thing by abandoning the open-ended release cycle in favor of the extremely long but predictable two-year deadlines.

      It sounds really weird and funny when a 2-year release cycle for an OPERATING SYSTEM is considered extremely long.

    4. Re:Balancing act by ILongForDarkness · · Score: 1

      For some linux users it isn't so much an operating system as a compile daily to see the new changes kind of mind set :-) Great OS that is rock solid, until you get the mindset of building everything from non-release grade source for the "must have" latest feature. Windows shoots you in the foot for you, Linux its a skill you have to develop ;-)

    5. Re:Balancing act by TheRaven64 · · Score: 1

      It would be if they were the ones writing the operating system, but when they're just the ones packaging a kernel, some userland tools, and some apps, all written by other people, it's a bit ridiculous that it takes two years. It also depends on how big a change you want between releases. OpenBSD releases every six months, but each release is an incremental improvement over the last, with maybe one or two interesting new features for any given user. There was a delay of several years between OPENSTEP 4 and Mac OS X 10.0 (OPENSTEP 5), but the number of user-visible changes was huge.

      --
      I am TheRaven on Soylent News
    6. Re:Balancing act by CastrTroy · · Score: 1

      Well, if you don't release often, how are you supposed to react to changes in the market. Compare with MS, who went 6 years between XP and Vista. Not only were people stuck using a 5 year old OS, which lacked basic stuff such as PNG support for the wallpaper (or the default browser), but they were also very much not in touch with what the market wanted when they released Vista. Now, had they follow a more linux/apple approach, and released something every 6 months to 1 year, they would have known much soon that they were headed down a bad path, and they would have also been able to get new features into the hands of users much sooner.

      --

      Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
    7. Re:Balancing act by SL+Baur · · Score: 1

      Now, had they follow a more linux/apple approach, and released something every 6 months to 1 year, they would have known much soon that they were headed down a bad path, and they would have also been able to get new features into the hands of users much sooner.

      It's been about 2 years since 10.5. I am not going to buy 10.6 for awhile and certainly not on Friday.

      But let's see. My vital app in Mac OS X is X11 so I can do work. It works great when Apple doesn't break it like they did in 10.5.

      Sadly, I have to agree that a long release cycle between O/S versions is probably a good idea.

    8. Re:Balancing act by Abcd1234 · · Score: 1

      If you have short deadlines, you end up with issues similar to the bugs Ubuntu needs to smooth out every release. If you go with "It'll be finished when it is finished", Your stable releases can become ridiculously out of date between versions. Debian did a good thing by abandoning the open-ended release cycle in favor of the extremely long but predictable two-year deadlines.

      'course, there's another, obvious solution: Code freeze at some predetermined date prior to deadline, followed by a stabilization phase before release. What, you can't get your code in before freeze? Tough shit, it goes into the next release.

    9. Re:Balancing act by ILongForDarkness · · Score: 1

      They are "just" packaging the kernel, selecting all the utilities they want to include and the version of the desktop. But the thing is the kernel hits new, interesting and stable releases relatively infrequently, same with the desktops. So the packagers have to wait for versions of the parts to come out that are worthwhile to push an upgrade on users.

  6. Similar by kondziu · · Score: 1, Interesting

    In my last job I had to fix a project management application, because, to allow user administrative privileges, it checked the condition: if (user_id == 1 || user_id == 18 || user_id == 23) {...}. It had a whole system for managing privileges, but someone got lazy at this particular point.

  7. Wow. Talk about old news. by Jack9 · · Score: 1, Informative

    This is literally a dupe from 2000. Wow. It'll take me a bit to look it up...

    --

    Often wrong but never in doubt.
    I am Jack9.
    Everyone knows me.
    1. Re:Wow. Talk about old news. by melikamp · · Score: 5, Funny

      The editor might have approved this submission just to meet some kind of deadline or a minimum requirement.

    2. Re:Wow. Talk about old news. by shish · · Score: 5, Insightful

      This is one of those stories where the story isn't the point, it's the comments that are worth reading, so it's only a problem if we have the same comments :-P

      --
      I mod down anyone who says "I will be modded down for this", regardless of the rest of their comment
    3. Re:Wow. Talk about old news. by pjt33 · · Score: 2, Interesting

      Quick, find the dupe and copy-paste all the +5 Insightfuls!

    4. Re:Wow. Talk about old news. by 7+digits · · Score: 5, Funny

      > it's the comments that are worth reading

      More specifically the comments in the article. I loved this one:

      "Back on Wing Commander 1 we were getting an exception from our EMM386 memory manager when we exited the game. We'd clear the screen and a single line would print out, something like "EMM386 Memory manager error. Blah blah blah." We had to ship ASAP. So I hex edited the error in the memory manager itself to read "Thank you for playing Wing Commander.""

      That's awesome.

    5. Re:Wow. Talk about old news. by CarpetShark · · Score: 1

      The editor might have approved this submission just to meet some kind of deadline or a minimum requirement.

      I believe the requirement you're referring to is this one:

      assert(suckiness >= 99.987);

    6. Re:Wow. Talk about old news. by GWBasic · · Score: 1

      "Back on Wing Commander 1 we were getting an exception from our EMM386 memory manager when we exited the game. We'd clear the screen and a single line would print out, something like "EMM386 Memory manager error. Blah blah blah." We had to ship ASAP. So I hex edited the error in the memory manager itself to read "Thank you for playing Wing Commander.""

      Back when I ran a dial-up, I hex-edited the "please register" pauses to say something like "loading, please wait."

    7. Re:Wow. Talk about old news. by Anonymous Coward · · Score: 0

      Just think if the Windows BSOD was changed to "Thanks for playing Windows! Goognight!"

  8. Sorry... by Anonymous Coward · · Score: 0

    10 Print "No"
    20 Goto 10

    1. Re:Sorry... by ZeroExistenZ · · Score: 0

      10 Print "No"
      20 Goto 10

      Please hand over your geekbadge...

      --
      I think we can keep recursing like this until someone returns 1
    2. Re:Sorry... by gt6062b · · Score: 2, Funny

      10 Print "No"
      20 Goto 10

      Please hand over your geekbadge...

      10 Print "No"
      20 Goto 10

  9. University Assignments. by Anonymous Coward · · Score: 5, Funny

    Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...

    Too much time playing games in class and I was about to fail the course unit if I didn't pass that one test (right at the end of a semester)

    So I ran the program, adjusted the output in a word processor, saved it as a file and threw some code hidden in the comments that read the file, outputted it and exited.

    Three minutes later my code was evaluated... I was the only one who passed.

    Fortunately, no one investigated too carefully at the time why I was the only one who passed, because after trying to fix the code later in my own time, I realized the source data we were all supplied was corrupted.

    Inevitably, Later the same lecturer came to the same conclusion when his program didn't work either and cornered me to ask why mine worked (of course he was suspicious). Thinking quickly, I told him my source data was corrupted and that I fixed that first so my program would work. I don't know if he believed me, but he accepted the story.

    Fortunately, I got away with it and I got to keep the pass.

    1. Re:University Assignments. by Anonymous Coward · · Score: 1, Funny

      This tactic works on the job too. I congratulate you on foresight.

    2. Re:University Assignments. by LaskoVortex · · Score: 2, Interesting

      We discovered that trick in O-chem lab too. You start with the percent yield to get an A on the lab and then back calculate your intermediate yields and amount of product you expected from the reagents you weighed. Fond memories.

      --
      Just callin' it like I see it.
    3. Re:University Assignments. by ShakaUVM · · Score: 1

      We discovered that trick in O-chem lab too. You start with the percent yield to get an A on the lab and then back calculate your intermediate yields and amount of product you expected from the reagents you weighed. Fond memories.

      Yeah, I breezed through chemistry with that. =)

      Once I dumped my entire experiment on the ground (and the teacher saw it) so I made sure my numbers weren't TOO accurate when I finished the lab.

    4. Re:University Assignments. by rew · · Score: 1

      Oh yeah. Similar here. In an assignment where we were supposed to learn the advantages of pointers, I had to swap two records in a list. So the idea is that you just swap the pointers, and keep the (large) records in the same spot in memory, to prevent having to move the (large) memory area holding all the data in the record.

      When I wanted to finish the assignment it didn't work as expected. After some frustration I ended up just swapping the whole records and then swapping the pointers back. The assignment got OK-ed.

      I had already learned to use pointers the proper way. I just had to pass the class goal achieved!

    5. Re:University Assignments. by istartedi · · Score: 1

      Let me guess. You parlayed that talent into a fortune for a while at the first company you worked for after graduating: Enron.

      --
      For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
    6. Re:University Assignments. by mrsurb · · Score: 2, Interesting

      What I learnt in Physics: First draw your lines-of-best-fit, THEN plot your points.

    7. Re:University Assignments. by Kentari · · Score: 2, Interesting

      This works well, until the teacher supplies clocks that have been tampered with to induce a 10% systematic error. You get to guess how many correct values of g turned up in that experiment... And who passed it.

    8. Re:University Assignments. by Sique · · Score: 1

      So basicly it's the StarTrek solution (as we all saw in "Wrath of Khan"): Modify the game if you can't beat it with the current rules.

      --
      .sig: Sique *sigh*
    9. Re:University Assignments. by mehrotra.akash · · Score: 1

      best solution take 1-2 readings VERY carefully and then use Excel goalseek to complete the rest have used C++ to solve many of my Maths P&C questions as well what would take me 10-15 mins atleast to solve and be done using a short 20-30 line prog in TC++(i think its even easier in python , dont know how 2 use it but)..

    10. Re:University Assignments. by Anonymous Coward · · Score: 0

      You thief! I have a patent on that NOVEL technique!

    11. Re:University Assignments. by consonant · · Score: 3, Funny

      Similar story.

      In one of my "Intro to C" mid-term exam, one of the (sit down in the 'puter lab and spew code type) assignments was a simple string manipulation exercise. After I was done with the program, while sitting around waiting for the output-verifying lab drone to come over to my place, I noticed all she was doing for the other folks with the same assignment question was key in the same series of words as test inputs. I saw this, and quickly whipped up another little program that basically displayed a prompt, and did a printf("{hard-coded desired output for same set of words}"); and ran this piddly little pile of 'code' when she stopped by my machine.

      Sadly, I passed..

    12. Re:University Assignments. by Aladrin · · Score: 3, Interesting

      You laugh, but that's the basis of 'Test Driven Design'. :D You were only supplied with 1 test, and you passed it. Had their been more tests, your code would have had to be what was really wanted.

      I've started to think about how a class could be run like that... Create a series of unit test sets that progressively test more of the program. For each assignment, give the students the next set of tests and have them code to make the tests pass. In the next class session, work to show everyone how to make it happen, then give the next set.

      --
      "If you make people think they're thinking, they'll love you; But if you really make them think, they'll hate you." - DM
    13. Re:University Assignments. by Anonymous Coward · · Score: 0

      And now you do accounting for multinational conglomerations?

    14. Re:University Assignments. by EdgeyEdgey · · Score: 1

      When I wanted to finish the assignment it didn't work as expected.

      Why were you not curious about this? You probably missed out on a much deeper lesson.

      --
      [Intentionally left blank]
    15. Re:University Assignments. by BlindRobin · · Score: 1

      I see a bright future for you in government service...

    16. Re:University Assignments. by rew · · Score: 1

      Sure, I'm still curious why it didn't work the way it was supposed to.

      I could have spent several hours to find a typo in my own code or maybe a bug in a library. To this day I continue to find typos in my code but less and less bugs-in-libraries.

    17. Re:University Assignments. by TheRaven64 · · Score: 4, Interesting

      My Physics teacher caught me doing that once. He pointed out that the intended learning outcome of the experiment was to understand the relation between the properties being graphed, and if I already understood this well enough to work out what the results should be then I had achieved the objective. One of the few teachers I've had who really understood what education was meant to be about.

      --
      I am TheRaven on Soylent News
    18. Re:University Assignments. by sanosuke001 · · Score: 1

      How do you muck up swapping two pointers? i mean;

      int *ptr1;
      int *ptr2;
      int *tmp;

      ptr1 = array1;
      ptr2 = array2;

      tmp = ptr1;
      ptr1 = ptr2;
      ptr2 = tmp;

      or am I missing something? (it has been a couple years since I've used C but I'm pretty sure that's right...)

      --
      -SaNo
    19. Re:University Assignments. by zippthorne · · Score: 1

      Michael Mann, is that you?

      --
      Can you be Even More Awesome?!
    20. Re:University Assignments. by GTarrant · · Score: 2, Interesting

      In one of my ASIC design classes, it was practically impossible for the professor to really go through everyone's design and ensure that they all worked properly - they were far too complicated. Likewise, it was difficult for students to ensure, while designing things, that the chip itself also worked as intended, because it was an error correction algorithm being implemented, so you had to sort of KNOW what a desired output would be. So the professor gave a sample input, and the intended output for this input, so that people could make sure their chips worked when they would run them in the design software.

      On the turn-in day, everyone turned in their huge heaps of paper that covered their design - again, practically impossible for the professor to 100% go through. Included also was a printout of everyone's signals within the chip - intermediate ones, and the final output. And of course, >95% of the things turned in gave the correct output and had everything correct inside.

      So the professor starts his lecture, and then stops and says "OK, everyone up!" And we headed to the computer lab, where he made everyone sit down in front of a computer, one by one, load up their chip, and gave a new input string (maybe 300-400 bits), and made each person run it.

      Approximately half the class had the output of their chip be the same output for the original "sample" input he had given so people could test - that is, their entire big ASIC (because it had to LOOK complex or it would be too obvious it didn't do anything) was essentially a giant set of fake elements which actually did nothing except give the appropriate output - for the ONE sample input.

      I have to admit, mine worked for the original input, but when he gave the new input, my output was correct for the first 399 bits - but the 400th was incorrect. It should have been a 1, I had a 0. It seems that no matter what the input was, my last bit (regardless of the number of input bits) had a stuck-at-0 fault. But since his sole sample input had a 0 as the final output bit, I never detected the fault. However, in this "second sample", the last 30 or so output bits were all 1's, and the difference between 29 '1" bits in a row and 30 "1" bits in a row in terms of looking at a long line quickly (as the professor was) is not noticeable. I saw it, but the professor didn't, and I got credit for the chip.

    21. Re:University Assignments. by rew · · Score: 1

      I was trying to write something like:

      swap (object *p)
      {
          object *tmp;
          tmp = p->next;
          tmp->next = p;
          p->next = p->next->next;
          p->prev->next = tmp;
      }

      which is complicated, and depends on the order you do things. Trying to do this in 2 minutes gives me the creeps that something is wrong, and I messed up the order. 20 years later I might write it (after getting coffee):

      swap (object *p)
      {
          object *pp, *q, *qn;
          pp=p->prev;
          q = p->next;
          qn = q->next; // Now we have the items in order pp p q qn, // and we need to swap p and q.
          pp->next = q;
          q->next = p;
          p->next = qn;
      }

      Which also shows that trying to optimize out a few local variables leads to unreadable code.

      I ended up writing:

      #define SWAP(a,b,tmp) tmp=a;a=b;b=tmp

      swaprecords (object *p)
      {
          object tobj, *tp, *q;
          q = p->next;
          SWAP (*p, *q tobj);
          SWAP (p-next, q->next, tp);
      }

    22. Re:University Assignments. by ari_j · · Score: 1

      That reminds me of a programming competition in college (not the same one from the Fucksort Incident, posted below), in which we were deducted points on one of the problems, which was to find the minimum amount of cable to connect several points on the surface of Mars, assuming it to be a perfect sphere of whatever radius. We appealed their ruling but were ignored. I never did figure out how the one team that got full points for that problem or the judges came up with their answers. For every other set of input, we had the same results as they did, but for the one set of input we gave an answer less than theirs by a few meters. We proved ourselves mathematically in a long letter to the appeals board and would have settled for being told how they came up with the "correct" answer, but to no avail. Thanks for reminding me, too. Now I get to lose sleep over that 2003 incident all over again.

      In your case, I would have told the professor "My code worked correctly but the input was corrupted, as you know. So I added a feature to correct for that by outputting the desired output. It was the only way to get the correct output given the input, and I stand by my method. However, if you correct the input and remove that feature the code will work as intended and, again, produce the correct output." Don't be so ashamed of slaying the horse correctly and then beating it a bit with a kludge afterwards. You did the right thing.

    23. Re:University Assignments. by Anonymous Coward · · Score: 0

      I had a similar situation, I used the professor's sample code from the previous exercise (which they allowed) to code the next exercise. I lost points because the TA said it "didn't look right".

      Turns out their code was using abs() on a random number between 0 and 1. Instead of fabs(). Not very random after that step.

    24. Re:University Assignments. by geminidomino · · Score: 4, Funny

      To this day I continue to find typos in my code but less and less bugs-in-libraries.

      That's because the ratio of code-bugs to library-bugs increases with the programmer's age, even if both the code and the library remain unchanged. </zen>

    25. Re:University Assignments. by tkatchev69 · · Score: 1

      This honestly irritates me. Granted the prof should have been more careful with the materials given, but that was clear cut cheating. I teach Comp Sci at a university, and my students could well be kicked out of school for this shennanigan. Not a good example for the students out there.

    26. Re:University Assignments. by Anonymous Coward · · Score: 0

      Hah, this really takes me back...

      In one of our assignments in the O.S. course, we were required to write a search program for Linux, somewhat like it's DOS counterpart (yeah, i know it's pointless, but just for training anyway).

      Turns out that my classmate's program was badly written, so that it got lost in the symbolic links while searching the directory tree. Time was running out, and the teacher was already analysing the group's works, just 2 groups from reaching them.

      The solution? Aw, crap, delete all those simbolic links right now! (we had root access by then)
      The operation and clear screen ended just seconds before the teacher finally came by their group. Crossing their fingers, they ran the search program to look for default sample file, and a few others afterwards. Luckily for them, the program didn't crash, found those files, and they passed!

      But the poor Linux... It was never quite the same again... Too bad for lab's interns!!!

    27. Re:University Assignments. by Eil · · Score: 1

      So everyone in that class failed the course because none of them (even the instructor) realized that the program input was bad? I'm not saying that the story isn't true, but this seems to be stretching the bounds of credibility.

    28. Re:University Assignments. by Legion303 · · Score: 1

      On his own time and under his own investigation while trying to make the code work, he discovered the original source corruption problem. He earned the goddamned grade regardless of whether he crammed himself into the higher education mold and came out with a deeper understanding of the problem than he would have if he had robotically coded something with clean input.

    29. Re:University Assignments. by Anonymous Coward · · Score: 0

      Admit it. You didn't write the string manipulation program in the first place...

    30. Re:University Assignments. by vivin · · Score: 1

      I once had an assignment during my sophomore year where I had to write a simple mathematical-expression evaluator in ADA (Simple addition, division stuff). My code would work fine until you added parentheses in the expression. Then it would give some weird error (don't recall the exact error). I noticed that if I removed all the parentheses it worked fine. No idea why. It shouldn't have, but it did. So before I parsed the expression, I removed ALL parentheses in the expression. I submitted the code and it passed the demo... no idea how. Heh.

      --
      Vivin Suresh Paliath
      http://vivin.net

      I like
    31. Re:University Assignments. by LaskoVortex · · Score: 1

      You get to guess how many correct values of g turned up in that experiment... And who passed it.

      None. And this had to be a full time staff lecturer or a high school physics class because no self respecting grad TA would bother with something like this. My policies were (1) show up (2) do not spill hazardous materials on yourself or others (3) don't break too much stuff. With those policies in place, still only about 60% passed. Something about #1 was difficult for my students. I think it was the 9 am lab time.

      --
      Just callin' it like I see it.
    32. Re:University Assignments. by janwedekind · · Score: 1

      Reminds me of Jan Hendrik Schön.

    33. Re:University Assignments. by dlanod · · Score: 1

      Back at university I had a lecturer that based his assignment evaluation off Test Driven Development (though I didn't realise it at the time, being a process-noob). Basically he gave us a list of test cases and the spec for the first assignment, a couple of extra requirements and more test cases in the second, and again for the third. I didn't realise the cleverness of this approach until several years out of uni and in the real world.

  10. Anonymous Coward by Anonymous Coward · · Score: 0

    Holy Crap -- among those who've been in the industry for more than a couple of years, who hasn't?

  11. Really? Not Slashdot's fault, if so... by Anonymous Coward · · Score: 2, Insightful

    The Gamasutra article is dated August 20, 2009. I doubt any Slashdot contributor submitted a link to a 2009 story back in 2000.

    1. Re:Really? Not Slashdot's fault, if so... by fractoid · · Score: 4, Funny

      John Titor sent it just before disappearing.

      Where'd he get to anyway?

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    2. Re:Really? Not Slashdot's fault, if so... by Trahloc · · Score: 4, Informative

      He's fighting in the civil war we're apparently not having, guess he fixed our timeline.

      --
      The Goal: A long simple life filled with many complex toys.
    3. Re:Really? Not Slashdot's fault, if so... by fractoid · · Score: 2, Funny

      I knew it! It really WAS true!

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    4. Re:Really? Not Slashdot's fault, if so... by smash · · Score: 2, Interesting

      Not having - yet.

      --
      I run: Windows, OS X, Linux, FreeBSD. Just because you have a hammer, doesn't mean everything is a nail.
    5. Re:Really? Not Slashdot's fault, if so... by 31415926535897 · · Score: 1

      Except, I recall that he had made a bunch of predictions that would lead up to the civil war. And (since they weren't too hard to guess), those predictions were correct, but still no civil war. How could he get the reasons for the cause of the civil war correct but not the actual end result?

    6. Re:Really? Not Slashdot's fault, if so... by citylivin · · Score: 1

      I believe he said that the start of the civil war would be sometime in this current presidents term. He also said that this president (obama, though not by name) would be far worse than the preceding president (BUSH) and usher in the civil war. I think he put the date of the war at 2012 with things being resolved in the the late teens 2015-2020 so it could still happen. Personally I thought that it would be the second bush term which would usher in the civil war (titors wording was vague (obviously) and said something to the effect of the president elected after bush, which could have been bush AGAIN or obama now).

      I had thought for sure that americans would have risen up during the bush term but i think i gave them too much credit.

      --
      As a potential lottery winner, I totally support tax cuts for the wealthy
    7. Re:Really? Not Slashdot's fault, if so... by Trahloc · · Score: 1

      I remember tracking it back in the day when it was still fresh and the dates weren't that far in the future. The civil war was supposed to start as a grassroots/behind the scenes in 2007 and blatantly obvious by late 2008 to even those of us who only follow non-tech/science news. Anything mentioned 2012-2015 is simply revisionist, confirm via archive.org or I'd say its a modern edit. He never made any hooks to the Mayan calendar from what I recall.

      --
      The Goal: A long simple life filled with many complex toys.
    8. Re:Really? Not Slashdot's fault, if so... by Anonymous Coward · · Score: 0

      According to Wikipeadia's John Titor, Trahloc more correct (but still not completely correct) than citylivin. Unless, of course, Trahloc is also a wikipeadian editor...;)

    9. Re:Really? Not Slashdot's fault, if so... by Anonymous Coward · · Score: 0

      Not having - ever.

      His predicted civil war started in late 2004/early 2005. His prediction has thus been proven wrong. Unless we go back in time and start a civil war, it's never going to happen.

  12. Wolf 360 hack by anss123 · · Score: 3, Interesting

    The deadline is looming, I can't spend much more time on this. So, I did the unthinkable -- I packed the controller id into the pointer parameter. I marked it as a horrible hack in a 4-line all-caps comment, and checked it in.

    Does not sound so horrible, just make sure the 1,2,3,4 pointers never point at anything "free()"able and it'll work fine.

    BTW, is that Wolf 360 game out?

    1. Re:Wolf 360 hack by andy_t_roo · · Score: 2, Funny

      my favorite hack is doing object click detection by rendering objects in a function pointer (4 byte pointers, rgba colour buffer .... ) -- when you click, a render pass is done with no lighting, effects, ... , and with each object coloured according <rgbaColour>object->onClick. To act on a click, read of the colour of the pixel under the mouse, and call it :)

      (oh, and solaris lies about giving you rgba -- it only gives you rgb -- my code would work on one of the uni servers, but not on another)

    2. Re:Wolf 360 hack by fractoid · · Score: 1

      I've done this with object IDs but... function pointers? That's deliciously evil!

      --
      Rampant carbon sequestration destroyed the Dinosaurs' tropical paradise. I'm here to help repair the damage.
    3. Re:Wolf 360 hack by denzacar · · Score: 1

      BTW, is that Wolf 360 game out?

      Wolf 359 game is out. Is that good enough?

      --
      Mit der Dummheit kämpfen Götter selbst vergebens
    4. Re:Wolf 360 hack by TheRaven64 · · Score: 1

      Packing extra data into a pointer isn't a particularly horrible hack. Most modern processors require aligned loads and stores, so you the bottom 1-3 bits of a pointer are almost always zero. Some architectures even ignore these bits, so your compiler will eliminate your mask as unrequired.

      Not only is this not particularly evil, it's not even new. Back in 1958, Lisp implementations were using this to store integers. Lisp is constructed from cells containing some data and a pointer to the next cell[1]. The data is a pointer to some other value. Lisp stored integer values inside this pointer by setting the low bit to 1 and using the other bits to store the value. On modern hardware you can do very cheap, overflow-checked, operations on this kind of boxed value (I've implemented it in a Smalltalk compiler and it's only slightly slower than unchecked operations in C).

      [1] Modern (and by modern I mean post-1970) Lisp implementations optimise this way beyond what I'm explaining here.

      --
      I am TheRaven on Soylent News
    5. Re:Wolf 360 hack by idonthack · · Score: 1

      Wikipedia says it came out August 18

      They were also giving out physical copies of it at Quakecon a couple weeks ago

      --
      Why is it that when you believe something it's an opinion, but when I believe something it's a manifesto?
    6. Re:Wolf 360 hack by jspenguin1 · · Score: 1

      I believe this is how Ruby does it as well. Any value with the low bit set is a 31 or 63-bit fixnum (depending on sizeof(void*)), and anything with the bottom three bits clear is a pointer to an object. Other low-bit patterns are used to identify true, false, and nil.

    7. Re:Wolf 360 hack by Anonymous Coward · · Score: 0

      Yes, I've only played it for 10 minutes, so I didn't get to try out the flesh destroying artifact yet.

    8. Re:Wolf 360 hack by QuoteMstr · · Score: 1

      My god: that's both disgusting and beautiful. It's like a Matisse painting. Cheers.

    9. Re:Wolf 360 hack by andy_t_roo · · Score: 1

      funny mod?!
      its only funny when wonder why you segfault because you forget to turn off fog rendering ...

    10. Re:Wolf 360 hack by julesh · · Score: 1

      my favorite hack is doing object click detection by rendering objects in a function pointer (4 byte pointers, rgba colour buffer .... ) -- when you click, a render pass is done with no lighting, effects, ... , and with each object coloured according object->onClick. To act on a click, read of the colour of the pixel under the mouse, and call it :)

      That's just... fucked up. You should be using the 16-bit (or smaller if possible) index into a table of objects in the scene, of course. Pack it into the most significant bits of the r, g and b fields. That way you'll be resilient to any rounding errors produced during rendering (as long as you round back to the nearest valid value rather than truncate when you read the ID back in), will work on hardware that doesn't support alpha correctly (which isn't limited to Sun machines, either; I once had a PC with an early ATI card that fucked up alpha channels more often than not), and will even continue to work if some fool decides to use a hacked driver that forces offscreen buffers to 16-bit for performance reasons (I've never encountered this happening, but have heard that it does from time to time when people are trying to game rendering benchmarks).

      Also, remember that once you've found which object was clicked, you can repeat the render but using vertex index as the colour rather than the object id. Just remember to set the shading mode to flat...

  13. Wrong question by julesh · · Score: 5, Insightful

    Have you ever needed to insert terrible code to make something work at the last minute?

    Wouldn't "have you ever shipped a product without needing to insert terrible code to make something work at the last minute?" be a more sensible question?

    1. Re:Wrong question by Opportunist · · Score: 4, Funny

      Probably. But reading a stream of "nope", "sorry", "you're kidding", "good one" ... answers leads to a lot of redundant mods but no good entertainment.

      --
      We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
    2. Re:Wrong question by jhol13 · · Score: 1

      Exactly.

      Like "when this method is called first time we know the second argument bogus".
      Or "the software is not capable of deleting all objects as there are pointers somewhere so make them kinda-static" (which leads to a very slightly erroneous behaviour rather than full collapse).
      Or "let's remove that mutex as it causes deadlock".

  14. Never by ChienAndalu · · Score: 3, Funny

    My boss however *only* does coding tricks. And he puts them in one big 1k line function.

    And is proud of it.

    1. Re:Never by tsergiu · · Score: 1

      My boss however *only* does coding tricks. And he puts them in one big 1k line function.

      And is proud of it.

      He's got a big bag o' tricks.

    2. Re:Never by matria · · Score: 1

      Reminds me of when I did some freelance perl coding for a wannabe ISP startup, back in the days when you could do that with a dozen modems. The boss showed me his pride-and-joy; the auto-sign up program he was personally writing - about 20 lines of C code and an absolutely enormous macro. I just nodded and made ooh-aah noises and went back to my perl coding.

    3. Re:Never by Guysmiley777 · · Score: 1

      A company I worked for took over polling of a restaurant chain's stores via analog modems. I was sent to get trained up on the polling system this company wrote for the restaurant chain. It was, I kid you not, entirely run on DOS batch files, Perl scripts and the Windows Task Scheduler. It would crash about once a week, so I'd get a page at 4:30 AM and have to remotely reboot one or more machines or rejigger some batch file. I was so happy when we finally got the OK to write our own polling solution.

      --
      Coding with assembly is like playing with Legos. Coding an application in assembly is like building a car with Legos.
    4. Re:Never by keytoe · · Score: 1

      My boss however *only* does coding tricks. And he puts them in one big 1k line function. And is proud of it.

      I laughed with empathy until I realized that this is actually sad.

    5. Re:Never by dkf · · Score: 1

      My boss however *only* does coding tricks. And he puts them in one big 1k line function.

      And is proud of it.

      So, how cool is it really to work for Larry Wall?

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
  15. No it isn't. by Anonymous Coward · · Score: 0

    Projects referred to include Doom 3 and the new Wolfenstein, which were not released in 2000. If it's a dup from 9 years ago, it was written by psychics.

    1. Re:No it isn't. by Anonymous Coward · · Score: 0

      Not necessarily:

      http://www.xkcd.com/628/

  16. Deadline is not the problem by nomad-9 · · Score: 2, Funny

    In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

    And putting such "if" statements is not solving the problem - not even temporarily - but hiding the bug.

    Right, nobody said it was easy. That's probably why software development is not for everybody.

    1. Re:Deadline is not the problem by 93+Escort+Wagon · · Score: 5, Insightful

      In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

      Yes, because deadlines are always reasonable and never pushed up. And change orders are a myth.

      --
      #DeleteChrome
    2. Re:Deadline is not the problem by oldhack · · Score: 5, Funny

      Slashdot sorely needs "douchebag" moderation.

      --
      Fuck systemd. Fuck Redhat. Fuck Soylent, too. Wait, scratch the last one.
    3. Re:Deadline is not the problem by glwtta · · Score: 1

      Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

      Right, even if the "real world" did work that way, there are still plenty of unreasonable deadlines to contend with.

      (though now that I think about it, the above was probably sarcasm; in which case: never mind)

      --
      sic transit gloria mundi
    4. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      "the real world" ahha, there's the misunderstanding.

    5. Re:Deadline is not the problem by dintech · · Score: 1

      He obviously works by himself in a rosy world where requirements and scope never change and nothing unexpected ever happens.

      In fact, I bet he's coding on a UNIVAC I in Pleasantville. That must be nice.

    6. Re:Deadline is not the problem by 91degrees · · Score: 1

      The developers had the task of producing the game to spec on time. The spec included not having this particular object. The game was released to spec and on time.

      Yes, they should have fixed this sooner. Since they didn't that isn't really a lot of help.

    7. Re:Deadline is not the problem by Aceticon · · Score: 1

      I've never had unreasonable deadlines, and never, ever had last minute changes on a project.

      *cough*

      Now ... could I have my pony?

    8. Re:Deadline is not the problem by Fross · · Score: 1

      Hahahahahaha! You've obviously never worked in the real world. Are you an academic?

      The boss comes in, 5 hours before an unmovable deadline, and says "The client has insisted you change feature X to do Y". Unfortunately, that's a fundamental change in the architecture.

      Or a nasty little hack. Which is the point here.

      Scope creep/changing requirements is not the developer's fault. It's the managers, but sometimes these things just can't be managed, and the client will get their way or the cheques don't get written.

    9. Re:Deadline is not the problem by Decameron81 · · Score: 1

      Pushing deadlines is the road to failure.

      --
      diegoT
    10. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      You're right, software development is clearly not for you.

    11. Re:Deadline is not the problem by devonbowen · · Score: 1

      I don't have a problem with last minute hacks to get something to work before a tight deadline. Unexpected behaviors pop up, deadlines are sometimes too optimistic, etc. What really pisses me off is when everyone else (read: management) thinks that that's the end of the line and that we don't need to clean it up in the next release. Basically, this means that the thing that wasn't my fault in the first place will end up biting me again a year down the road. So I usually end up cleaning up stuff like this on the sly.

    12. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      Right, nobody said it was easy. That's probably why software development is not for everybody.

      Oh come on. We all know "Even a child can do programming. Little Teddy made a video game just last week. All you have to do is...."

      I'm afraid that I've seen more bad code than otherwise over the last few years, and I'm firmly convinced that software development really isn't for everybody. Just those willing to work for $15/hr or less, regardless of actual skills or aptitude.

    13. Re:Deadline is not the problem by HighFalutinCoder · · Score: 1

      Change Orders really are a myth where I work, unless "Oh, we changed our minds about that piece of the project. We need you to add a whole new section of logic and a new report by the end of the day," counts.

    14. Re:Deadline is not the problem by MadKeithV · · Score: 1

      He obviously works by himself in a rosy world where requirements and scope never change and nothing unexpected ever happens.

      In fact, I bet he's coding on a UNIVAC I in Pleasantville. That must be nice.

      No, I think he's working for the government.

    15. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      there is +5, Funny for that

    16. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      And change orders are a myth.

      Change requests ... I swear, sometimes I just want to kill my clients!

      Client: Oh, did I forget to mention...

    17. Re:Deadline is not the problem by nomad-9 · · Score: 0, Flamebait

      In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.

      Yes, because deadlines are always reasonable and never pushed up. And change orders are a myth.

      Nope. Deadlines are often unreasonable. Welcome to the real world. But as a good software developer, you should be able to cope with that too, and without last-minute hide-the-problem hacks.

    18. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      Wait, impossible deadlines and change requirements that screw a project?

      INCONCEIVABLE!

    19. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      We had a milestone deadline and were no-way ready for the deliverable to our foreign customers. The head engineer ran a demo (faked) and the customers all smiled and nodded.

      Funny part was the boss standing at the back of the room sweating and flinching each time a non-working module was to be demoed and gasping when it "worked". He had no idea our software could do all that stuff!

    20. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      If you've got enough time to do it the right way, you're wasting company time and money. Get dirty and hack it out.

    21. Re:Deadline is not the problem by russotto · · Score: 4, Insightful

      Nope. Deadlines are often unreasonable. Welcome to the real world. But as a good software developer, you should be able to cope with that too, and without last-minute hide-the-problem hacks.

      Wait, you were serious? Does your hair come to points on the side of your head, by any chance?

      If I could cope with unreasonable deadlines without some sort of nasty compromise, I wouldn't be developing software. I'd be turning water into wine, holding back the tide, etc. "Good software developer" doesn't mean "miracle worker". If the time isn't there before the deadline to solve the problem correctly, either the deadline will be missed or the problem will be unsolved or poorly solved. That's close to a tautology; it's implicit in the term "unreasonable".

    22. Re:Deadline is not the problem by adisakp · · Score: 1

      And putting such "if" statements is not solving the problem - not even temporarily - but hiding the bug.

      Wait, I though 'goto' was bad... now 'if' is bad as well ?

    23. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      You should stop pretending to be "involved" with software development.
      You're obviously not.
      My guess is you're a webmaster.
      After all that's the position all people who didn't make it end up.

    24. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      +5 funny followed by -4 troll

    25. Re:Deadline is not the problem by tholomyes · · Score: 2, Insightful

      Nope. Deadlines are often unreasonable. Welcome to the real world. But as a good software developer, you should be able to cope with that too, and without last-minute hide-the-problem hacks.

      This "real world" of yours sounds a lot like programming in a bubble. Aside from the constraints of working on top of other's libraries, operating systems, or web browsers, software will always have bugs, and they may not always be under your control. You'll have to defer the lower priority bugs to meet your release date, but without sufficient time to address them-- say, a last-minute bug that would require a significant rewrite of a subsystem that you didn't even author-- you can at least try to make the problem less painful in the meantime.

      --
      When did the future switch from being a promise to a threat? -C. Palahniuk
    26. Re:Deadline is not the problem by nomad-9 · · Score: 1

      Wait, you were serious? Does your hair come to points on the side of your head, by any chance?

      If I could cope with unreasonable deadlines without some sort of nasty compromise, I wouldn't be developing software.

      No, I have actually my hair combed backwards. Dealing with unreasonable deadlines doesn't have to necessarily cause last-minute crappy hacks such as the one reported.

      You make compromises in your code all the time by taking into account your deadlines. You plan ahead. When was the last time you developed with no pressure?

    27. Re:Deadline is not the problem by nomad-9 · · Score: 1

      You should stop pretending to be "involved" with software development. You're obviously not. My guess is you're a webmaster. After all that's the position all people who didn't make it end up.

      Your guess is wrong. I have been programing since 1994. You "obviously" don't understand the difference between working under pressure with unreasonable deadlines, which happens more often than not, and doing crappy programing that have you do these last-minute code hacks unworthy of what you pretend to be.

      After all, "people that didn't make it" & substandard developers like to find excuses for their own failure.

    28. Re:Deadline is not the problem by nomad-9 · · Score: 1

      You'll have to defer the lower priority bugs to meet your release date, but without sufficient time to address them-- say, a last-minute bug that would require a significant rewrite of a subsystem that you didn't even author-- you can at least try to make the problem less painful in the meantime.

      What I'm trying to tell you, is that, when you hide the bug, you're not making the problem less painful. On the contrary. For the rest, read my previous response.

    29. Re:Deadline is not the problem by Anonymous Coward · · Score: 0

      Oh god you're so wrong.

      You keep forgetting:

      1) not all bugs are under your control
      2) not all bugs are equally detectable
      3) most of the time the whole architecture is not under your control
      4) your bug testers don't always perform like superhumans.

      You sound like the sort of person who _never_ had to deal with a large team project. Let me give you a tip: you have to work with crappy programmers too, coz 99% of the time that's all you got. And you have to put in the extra effort to make their code work too.

      You sound horribly pretentious and uptight.

  17. Sucker punch by Anonymous Coward · · Score: 4, Funny

    When my deadline comes up and I haven't produced I wait for my boss to ask me for the code then I sucker punch him and run away. The trick is to hold down short term contracts and give false references and hire someone to back them up (another dirty trick). That also makes it easier to dodge the cops when your boss presses charges. It's getting harder though with all this talk of test driven development and short incremental releases. Then the trick becomes to write the most meaningless trivial unimportant tests first - but crucially tests that you can make pass quickly so you don't have to do any real work.

    (For anyone insane enough not to realise it, this is a joke. Don't try this at home...or at work).

    1. Re:Sucker punch by pooh666 · · Score: 1

      Sure thing Wally, I won't say a word...

    2. Re:Sucker punch by Daravon · · Score: 1

      Posted anonymously due to being John Romero, who is going to make us his bitch?

      --
      I traded all my mod points for these magic beans.
  18. Game Art by j-stroy · · Score: 4, Interesting

    A 3d model export would break regularly screwing up the texture map orientation on certain polygons. The godawful export couldn't be fixed on the deadline, and risk management said best not to touch it cuz EVERYTHING might bust, let alone all the coders being nailed to the wall by the ship date. So I fixed the model files in an ascii editor. All the art builds that had tweaks needed this "touch" Since it was a hockey game, you can imagine how many goalie pads that was. Oh yeah, you couldn't see if the fixes were correct except in the game engine after more pipeline.

    Technically not a code fix, but still a valid solution.

    1. Re:Game Art by Anonymous Coward · · Score: 0

      Why wouldn't you script the "touch" and add it to the art pipeline? It's not like you're changing the export, which makes backout trivial if something goes wrong ...

    2. Re:Game Art by j-stroy · · Score: 1

      haha yeah, theory, all theory. practice is different.

      K, if I remember correctly, the bad poly's were not consistent, something funky in some source models combined with a bad exporter. So some models would barf on some polys, but not the same ones each time. If the model was edited that would change vertex and polygon numbering. Also, since it was an orientation thing in texture space, it wasn't trivial to trap/mask for. Absolute poly and UV numeric order isn't guaranteed, its relative. So scripting the fix would only reproduce a fix that had already occurred and may not reoccur.

      Also I recall some legacy evilness about exporting animations which was why the source art couldn't be fixed. Believe me I wan't happy about it, was just tasked with fixing it. Not my design. But isn't what this thread was about?

  19. seen some bad shit. by Ziest · · Score: 5, Interesting

    I once worked at a Fortune 25 company in Chicago. They had this ENORMOUS mainframe program written in COBOL that ran their order inventory system which accounted for 20% of the companies revenue. All the guys who wrote this grunting pig of a system had either retired or had passed away. In the middle of the code was the following;

        *
        * We don't know what this does.
        * Please leave it alone !
        *
            SET INSIDE-INDEX TO 1.
        *
        * We don't know what this does.
        * Please leave it alone !
        *

    If this statement was commented out or removed the system stopped working. No one could find the problem. People had spent years looking for it but the code was such a mess and the documentation was so useless that they just left it alone and made a note that when the order inventory was re-done to make sure they left this "feature" out. I have been told that many old system have similar problems.
     

    --
    Another day closer to redwood heaven
    1. Re:seen some bad shit. by setagllib · · Score: 1

      Even the most primitive data flow analysis would help track that down, but if the code isn't written with assertions all over, you never really know if it's consistent with assumptions or only fooling you all along. I don't write anything without assertions these days.

      --
      Sam ty sig.
    2. Re:seen some bad shit. by Heart+Driven · · Score: 0

      I once worked for a Belgian reseller company using PROGRESS. Every procedure was build on top of another and they were all using one user authentication procedure. One day the authentication server was down and no one could log in, causing the company to be down all night (they had an Australian subdivision using their program as well) with huge losses as a result. A quick fix was introduced, replacing the 100-line authentication script: DEFINE OUTPUT PARAMETER opSuccess AS LOGICAL. ASSIGN opSucces = 1. They forgot about it and only weeks after they fixed it.

    3. Re:seen some bad shit. by Anonymous Coward · · Score: 0

      Did this software rhyme with "ebombetry"?

    4. Re:seen some bad shit. by Anonymous Coward · · Score: 0

      I don't write anything without assertions these days.

      Sort of like

      int assert_count = 0;

      void assert( ... )
      {
              assert_count++;
              _assert( ... )
      } ...

      int main
      {
              printf( "hello world\n" );
              assert( assert_count > 0 );
      }

    5. Re:seen some bad shit. by KonoWatakushi · · Score: 1

      Assuming that the compiler is working properly, probably so. However, it wouldn't be the first time that I have seen code which when removed breaks things horribly, even though it shouldn't. (It is also not rare to see code break at higher optimization levels...)

      Agreed about the assertions. Does cobol even have those though?

    6. Re:seen some bad shit. by Liquid+Len · · Score: 1

      Yeah, well, why bother removing it, then ? If it ain't broken, just don't fix it...

    7. Re:seen some bad shit. by phantomfive · · Score: 1

      Reminds me of one of my professors, when he was in college he had to write his programs on punch cards and take them in to be run in a batch job, then he'd get a printout of the result, debug and try again. Probably from the same time era as your story. One time he got a bug he couldn't figure out at all, but the operator told him, "oh, there are some bad memory segments. Try moving your program around in memory a bit and doing it again." Poor guy said he had no clue how to do it. And I'm glad I don't have to do it.

      --
      Qxe4
    8. Re:seen some bad shit. by Anonymous Coward · · Score: 0

      Slightly off-topic, but...

      When in university, I at one point had to use a java class file reader by written by a former employee. At one point it had some code creating a 32 bit int from 4 bytes. In Java, this is not trivial because of the lack of unsigned types and corresponding casts (e.g. see here).

      Anyway, the code had the brilliant comment:

      // I think it's safe to say that I don't know what I'm doing here.

      It turned out to be completely wrong...

      Another beautiful example:

      In ANSI-C, declarations can only be done at scope start. It may therefore make sense to insert a block in the middel of a function.
      At one occasion, the resulting code looked like:

      if (....) { ...
      }
      { ...
      }

      Then, somebody inserted an else that he thought was missing:

      if (...) { ...
      } else
      { ...
      }

      We changed that else into the comment "Definitely no else here!"

      Ruben

    9. Re:seen some bad shit. by lawrence.a.sim · · Score: 1

      Reminds me of our load-bearing comment, you remove it or shrink it in any way and the app would fail to compile...

    10. Re:seen some bad shit. by psm321 · · Score: 1

      I saw something similar where informal documentation (written many many years after the fact) on a very old system that was still in use said "we don't know what this loader parameter does. if you know, please tell us"

    11. Re:seen some bad shit. by Anonymous Coward · · Score: 0

      Does this software rhyme with "ebombetry"?

    12. Re:seen some bad shit. by obarel · · Score: 1
    13. Re:seen some bad shit. by setagllib · · Score: 1

      If it doesn't, it is still far better for your software quality to use cpp (literally, the C preprocessor) to get assertions into the source code. There is basically no alternative to assertions, except for expanding them to a manual if each time, which is *still* better than not having them at all.

      --
      Sam ty sig.
    14. Re:seen some bad shit. by hesaigo999ca · · Score: 1

      I myself have seen some comments working for a few different companies that would lead
      me to believe that no one ever bothered checking the code.
      Stuff like "You suck" or "What a dushbag"... even "Mike doesn't know sh*t"...
      makes me wonder what the programmer REALLY thought about his boss or coworkers.

      Maybe it was meant as a joke, and meant to be removed before releasing, but I am sure I could find a hexeditor and open the app up at any of our suppliers, and see the comments in their full glory!

  20. return, break, continue? by krischik · · Score: 3, Informative

    Have you ever wrote a function / procedure with more then one return statement? Or used break or continue in a loop? Then you can use goto as well. From a structure point of view goto, break, continue and return are all unconditional jumps. They are one of a kind. And looking back in retrospect: Since goto need to be paired with a label it's the least evil of the group.

    Note that Pascal the archetype of structured programming had goto but it did not have break, continue or return.

    1. Re:return, break, continue? by pjt33 · · Score: 1

      Since goto need to be paired with a label it's the least evil of the group.

      I don't follow that argument. Why wouldn't return, which doesn't need a label because it's always unambiguous, not be less evil?

    2. Re:return, break, continue? by beelsebob · · Score: 1

      The reason I consider goto evil is because it obfuscates control flow for the reader. They must search for the label to find out where control is going to. Return, break and continue do not have this effect.

    3. Re:return, break, continue? by Viol8 · · Score: 1

      "They must search for the label to find out where control is going to"

      And how hard is that exactly?

      / in vi. BFD.

      "Return, break and continue do not have this effect."

      With a return you have no idea where its going to return to just by looking at a specific function. How is that clearer?

    4. Re:return, break, continue? by maxwell+demon · · Score: 1

      The reason I consider goto evil is because it obfuscates control flow for the reader. They must search for the label to find out where control is going to. Return, break and continue do not have this effect.

      For break/continue, they have to search for the beginning/end of the construct it belongs to instead. And unlike a label, you cannot just use your editor's search function. Also, if you are in a switch inside a loop, break will apply to the switch, while continue will apply to the loop. Now you might argue that if you have any problems to find the beginning/end of your loop, then you probably have a design problem. But the same holds if you can't find your label.

      Actually, I've never actually found the need to have a goto in my code. However if I ever come across a case where it makes sense, I'll not hesitate to use it. There only strict rule about goto IMHO is:

      Never use a goto to jump into a block. This includes "blocks" formed by a goto and its label.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    5. Re:return, break, continue? by krischik · · Score: 1

      An unconditional jump consists of of two parts: the source and the destination of the jump. With goto both parts are maked inside the - with the other three only one half - the source - is visible in the code.

      Imgagine:


            procedure Some_Function
            is
            -- 200 lines of code.
      <<Exit_Function>>
            end Some_Function:

      You see the label and you know - there must be a goto somewhere - let's have a look for it.

    6. Re:return, break, continue? by krischik · · Score: 1

      True: You don't have to search for label. But how about the other way around: You are at the end of a loop or function - how do you know that there is or is not a break or return somewhere above?

      An uncoditinal jump consists of two parts - source and destination and only goto will clearly mark both of them. At least you know there is something to search for which is a lot better then not knowing that you should be searching.

    7. Re:return, break, continue? by FourthAge · · Score: 1

      In some cases, goto actually makes the meaning of C code clearer. There are plenty of examples from the Linux kernel where goto is used for exactly this purpose; I posted one above.

      Arguably, this is a problem with C, rather than a benefit of goto :).

      --
      The tao of democracy: the government you can vote for is not the real government.
    8. Re:return, break, continue? by Anonymous Coward · · Score: 0

      The label is the problem, not the goto, and that's where you don't get it. Returns go back to the caller. As Barney Stringdup said, it's NOT the seeing a goto that makes a sinking feeling, it's seeing that label in the middle of something -- where in the world (and one or many places) did the goto come from? EG, seeing a label means (most probably) that something *else* jumps to here -- but unless it's obvious and nearby in the code, you've suddenly got a complete mystery on your hands. How many things reference this label? (I'm speaking here of labels that aren't subroutine or class member declarations).

      Of course, nowadays my laser beats your chainsaw. Now that a compilation of even complex code takes only a few seconds -- just comment the sucker out and recompile, you'll probably find all that. That is, if you have the source to all the modules in the project, which of course you may not. Then you just get link errors and are really in a (un)fix(able).

      Yeah, great coders can push an address(es) on the stack and execute a return to do fun things -- but no one else later can figure them out easily. In other words, create code that works, but still sucks. Is that good in some way? I've been at this long enough to have to return to decades old code of my own for possible reuse.
      No way the super tricks are cool unless there's like a paragraph or more of explanation in the code just before using the trick -- so the poor maintainer (also me) can "get it" again.

    9. Re:return, break, continue? by hibiki_r · · Score: 1

      If your function is 200 lines long, you've already failed.

    10. Re:return, break, continue? by Anonymous Coward · · Score: 0

      Not recently (ie. last 10 years), for the same reason that I don't use goto. I prefer to minimize how much I have to think about my code.

      Worrying about where I have to free resources makes life more complicated than it needs to be.

      This applies to both whole functions and individual loops within the structure.

    11. Re:return, break, continue? by krischik · · Score: 1

      ROTFL

      Yes, that's the theory. In praxis somebody else might have failed and you have to fix the mess. And there will be lot's of break and return statements to make things even more interesting. :-)

    12. Re:return, break, continue? by Carewolf · · Score: 1

      -- just comment the sucker out and recompile

      I find CTRL+F to be faster.

    13. Re:return, break, continue? by SL+Baur · · Score: 1

      Since goto need to be paired with a label it's the least evil of the group.

      I don't follow that argument. Why wouldn't return, which doesn't need a label because it's always unambiguous, not be less evil?

      I don't follow your statement. An IDE can always follow a local goto to its intended target label via `M-.' or whatever. A return is ambiguous as to where flow of control goes next. There's no way that an IDE (or a compiler) has of knowing which routine you want to see the source code of. That's always a runtime issue. The best an IDE can do is present a menu of calling sites in the source code it knows about.

  21. Thread Manager by ShakaUVM · · Score: 1

    Due to the vagaries of setjmp and longjmp (we were writing a thread manager) and the fact that in C, functions can only return one value we got into a situation where threads (by spec) must be allowed to return an integer, AND the thread manager would need to report if the thread died to the calling function as well (also using the same int). Our group batted it around for a while and didn't see any solutions that were threadsafe under all conditions, so we ended up just specifying that threads couldn't return -1. =)

    Cost us 5% off the final grade, I think.

    1. Re:Thread Manager by Lally+Singh · · Score: 1

      Google the term "out parameter." Or "Return a struct." Or "Bit-shift OR into a larger type."

      If that's all too much. Remember that a double has 52 bits of mantissa.

      --
      Care about electronic freedom? Consider donating to the EFF!
    2. Re:Thread Manager by Anonymous Coward · · Score: 0

      "and the fact that in C, functions can only return one value"

      Not if you use a struct of multiple values and return that.

    3. Re:Thread Manager by TheRaven64 · · Score: 1

      I'm not sure how you wrote a thread manager using setjmp()/longjmp() since those trample over the stack - you can't longjmp() down the stack, only up it, although I suppose you could setjmp() then modify the stack pointer and then longjmp() with a new stack, although whether this works is highly implementation-dependent. The functions you are probably looking for are in ucontext.h. Others have pointed out that you can do multiple return values in C, but the most common way of implementing this is to use thread-local storage. If you are implementing userspace threads, you can implement TLS by creating a static array indexed by the thread id.

      One of the most interesting bugs I've fixed was in an Objective-C compiler, where the code was crashing on load (before it actually got to any code) except in cases where I put a constant string somewhere in the source file. It turned out that the compiler was not NULL-terminating constant strings, including the superclass name that the runtime library was using to insert the new class into the class hierarchy. Adding a constant string meant that the data segment was reordered and a 0-initialized integer followed the constant string, which the runtime then treated as a terminator.

      --
      I am TheRaven on Soylent News
    4. Re:Thread Manager by ShakaUVM · · Score: 1

      >>Google the term "out parameter." Or "Return a struct." Or "Bit-shift OR into a larger type."

      No shit. We'd have returned a struct if we could have. If it was just the thread manager dealing with the return value, it would have been easy.

      Did you miss the part where threads were required by spec to return an int? Since this value could be directly passed to another thread, we couldn't adjust the return value to a struct.

      I think most other people in the class set a static variable indicating error, but we refused to do this as it wasn't threadsafe.

    5. Re:Thread Manager by ShakaUVM · · Score: 1

      I'm not sure how you wrote a thread manager using setjmp()/longjmp() since those trample over the stack - you can't longjmp() down the stack, only up it, although I suppose you could setjmp() then modify the stack pointer and then longjmp() with a new stack, although whether this works is highly implementation-dependent

      Yeah. (And this was from March 1999, so my memory is a little fuzzy on the details.)

      IIRC, we'd statically allocate a stack, by having something like int my_stack[10000] inside a function which never returns, and then each thread would get a static stack inside of that space. Or something like that.

      As I said in the other thread, we were kind of hosed by the spec, which stated that the threads had to return an int, and since not only did our thread manager spawn threads, but other threads could spawn threads, we couldn't alter this to be a struct, since they required ints to be returned. We didn't want to do what most did (which is to have a static value to hold the error status on a terminating thread), since it wouldn't be threadsafe in a preemptive environment.

      I suppose we could have a static array keyed by the thread value to hold the error status. I guess, technically, it wouldn't be threadsafe either if it set an error status, terminated, and then got preempted, spawned a new thread with the same id, which then could immediately terminate and clear the error status. Unlikely, I guess, but we valued thread safety over anything else. I'm sure there's some way of doing it safely, though.

      Thanks for the reference on ucontext. =)

  22. Train simulation by LucidBeast · · Score: 5, Interesting

    Way back we had a project where we had to simulate entire train traffic entering Helsinki train terminal. Someone else had made the simulator and it ran pretty neatly, but unfortunately crashed mysteriously after about four - six hours of simulation time. Our customers were coming the on monday and I spent my sunday trying to figure out how this simulation worked and what crashed it. Finally I caught the problem, which was as simple as some null pointer to a train schedule or something similar which needed to be referenced. I couldn't figure out why it was null in time, so I just added test for null pointer, which skipped said code. Program ran fine and we got our money. Never figured out what was wrong with it. Luckily it was only a simulation.

    1. Re:Train simulation by Anonymous Coward · · Score: 0

      Never figured out what was wrong with it. Luckily it was only a simulation.

      That you know of....

    2. Re:Train simulation by Shimmer · · Score: 1

      Ender's Game, Steampunk Edition.

      --
      The most rabid believers in American Exceptionalism are the exact same people whose policies are destroying it.
  23. Study Assignment by LKM · · Score: 5, Funny

    This was a pretty important assignment back when I was studying computer science. It added to the final mark mark for that particular class. The task was to write a reasonably complex application in Prolog or some functional programming language, I can't remember which it was. I think the goal was to pair males and females based on their preferences, and find the optimal solution. Of course, I screwed up royally, and nothing worked five minutes before I had to demonstrate my solution.

    So in the final five minutes, I changed my code so it would avoid the parts which put it into an infinite loop, and instead simply output a random result. My goal was to tell the prof that it had worked a few minutes earlier, and that I didn't know what had gone wrong, and could I please have another week?

    So I demonstrated my app, it gave its random output, and I was about to start with my "damn, it used to work properly" spiel when he said (and this is actually true, even though it sounds unbelievable):

    "That's great! The result is correct, and your app is also quite a bit quicker than my own implementation of the problem. Congratulations, I think you're the only one so far who managed to get the correct result so far."

    I was so taken aback that I probably just stared at him for a few seconds. Then, I stupidly said "So... You want to see my code?" but he was like "No, the result is correct, and your implementation is very fast, so I don't need to see the code. Good job. Send in the next guy."

    And so I did.

    1. Re:Study Assignment by u.hertlein · · Score: 4, Insightful

      "That's great! The result is correct, and your app is also quite a bit quicker than my own implementation of the problem. Congratulations, I think you're the only one so far who managed to get the correct result so far."

      I was so taken aback that I probably just stared at him for a few seconds. Then, I stupidly said "So... You want to see my code?" but he was like "No, the result is correct, and your implementation is very fast, so I don't need to see the code. Good job. Send in the next guy."

      This is so sad. He notices your code is faster and he's not the least bit curious? (I presume he's some kind of CS prof.) Anyway, good for you, but still... :-(

      --
      Geek by Nature - Linux by Choice.
    2. Re:Study Assignment by Opportunist · · Score: 1

      I'd sue your prof, he obviously took your program and sold it to various dating webpages now cluttering the 'net."

      --
      We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
    3. Re:Study Assignment by Sique · · Score: 1

      Sometimes you just don't want to know what has beaten/bitten you.

      --
      .sig: Sique *sigh*
    4. Re:Study Assignment by hey · · Score: 1

      A good tip. Just output random stuff. Probably how internet dating sites do it anyhow.

    5. Re:Study Assignment by mehrotra.akash · · Score: 2, Funny

      the opposite happened to me today, made a C++ program to demonstrate the use of classes and made full use of constructors, destructors,data hiding and DMA show it to the prof., he stares at it for 5 mins and then tells me to make everything in the class public and do the thing using arrays only....

    6. Re:Study Assignment by dintech · · Score: 1, Informative

      Probably he didn't spend much time implementing his version so wasn't too worried. He probably invests most of his time in actual research instead of pesky undergrads.

    7. Re:Study Assignment by LKM · · Score: 2, Interesting

      He had to grade about 100 people in one day, so I guess he didn't want to spend too much time on each individual student. I'm also not sure whether he actually personally implemented his version, or whether it was one of his assistants.
      He was a pretty good prof, otherwise.

    8. Re:Study Assignment by Anonymous Coward · · Score: 0

      Haha,

      the night before you had to demonstrate the assignment, said prof was sat infront of his machine unable to make it work, so he too made a random pairing.

    9. Re:Study Assignment by Lally+Singh · · Score: 1

      Sometimes a CS prof hasn't spent their entire career in the same area as a single undergraduate course, and just relearned enough to teach the course & answer student questions on it.

      --
      Care about electronic freedom? Consider donating to the EFF!
    10. Re:Study Assignment by craagz · · Score: 1

      You must have been within the 1%

    11. Re:Study Assignment by LKM · · Score: 1

      That's probably what happened :-)

    12. Re:Study Assignment by LKM · · Score: 1

      I think in my case, it was more along the lines of within the 0.001% :-)

    13. Re:Study Assignment by witherstaff · · Score: 1

      Matters on the dating site. Most have fake female profiles that send you messages, requiring you to pay to simply read the damn thing. Nothing like the prospect of an 18 year old cheerleader to get a guy to whip out his credit card. I wish I was just being glib.

    14. Re:Study Assignment by houghi · · Score: 3, Interesting

      In Real Life dating agencies, there are often a lack of males. So one person who owned it often dated the women, just to keep them on longer and to get more money from them. They were not in the dating game, they were in the 'get money from desperate souls' game.

      The reason (his words) was that women were less afraid to admitting to each other that they were unable to find a partner, where male ego's would never admit such a thing.

      Obviously with the anonymity that is The Internet, this difference is gone and any man now gets ripped of as well.

      --
      Don't fight for your country, if your country does not fight for you.
    15. Re:Study Assignment by MorpheousMarty · · Score: 1

      Stay tuned for tomorrow's article: Dirty tricks to grade students' work

    16. Re:Study Assignment by Anonymous Coward · · Score: 0

      Hi. I'm the engineer that designed your roads/buildings/cars/airplanes/other safety device. I passed school this way also and look forward to meeting you in academic dishonesty hell.

    17. Re:Study Assignment by Anonymous Coward · · Score: 0

      Think about it, that poor professor is sitting through probably 30-50 demos and thus far only one has worked so he has a few more dozen failures and excuses to sit through. Hes probably relived and grateful this one is done.

    18. Re:Study Assignment by LKM · · Score: 1

      Funny. See you there.

    19. Re:Study Assignment by bonch · · Score: 0

      In high school, our computer science class was sending teams of students out of town to a computer fair to show off our programming projects. Our group, the lazy Quake players, did a project on neural networks, and I threw together a C++ program that did nothing else but accept a value, do busy-looking math operations, and output the result. Nobody noticed.

    20. Re:Study Assignment by GodfatherofSoul · · Score: 1

      Sometimes students have such proven talent that professors don't really question the means. Or, a student is such a known quantity the professor doesn't feel he needs to waste time on someone who already gets it.

      --
      I swear to God...I swear to God! That is NOT how you treat your human!
    21. Re:Study Assignment by SL+Baur · · Score: 1

      I was so taken aback that I probably just stared at him for a few seconds. Then, I stupidly said "So... You want to see my code?" but he was like "No, the result is correct, and your implementation is very fast, so I don't need to see the code. Good job. Send in the next guy."

      This is so sad. He notices your code is faster and he's not the least bit curious? (I presume he's some kind of CS prof.) Anyway, good for you, but still... :-(

      Yeah, sad. When I was demoing my OS class project I was told that it was the best project they had seen in a decade and a half of teaching the course and could they please keep a copy of the source. Which absolutely worked for me. I got it done so fast I had time to implement online help in the shell which rather stunned them.

      This was in HP-1000 assembly and the main display was a row of LEDs on the front. I arranged my idle task to flash different LEDs as it got scheduled. The TA had earlier issued a challenge (for someone like me) that he liked to crank the timer up to max and watch student projects crash (the HP-1000 had 3 possible time intervals and the fastest interval was very fast). I added a command to my shell to allow changing the timer interrupt at run time. The LEDs showed that I was spending a lot of time in the scheduler (I didn't bother to optimize it once I knew it worked) in the shortest timeslice mode. But it worked and the terminals were still responsive.

      Absolutely the most fun class I've ever had. The prof even had me teach for a day towards the end of the semester on VMS IPC mechanisms.

  24. Example by Anonymous Coward · · Score: 5, Interesting

    Example?  Right here:
    #include <stdio.h>

    void    *f(void)
    {
    a:
        printf("Here!\n");
        return &&a;
    }

    int     main(int ac, char **av)
    {
        goto *f();
        printf("There\n");
        return 0;
    }

    1. Re:Example by EvanED · · Score: 1

      What exactly is that a good solution to?

    2. Re:Example by Anonymous Coward · · Score: 0

      Obfuscation (at best). This is very unsafe code. It does a non-local goto from one function into another, and as that function exits it deallocates the other function's stack frame (or at least tries to), and returns to... who knows! But I found it curious one can even write such a thing.

    3. Re:Example by 7+digits · · Score: 5, Informative

      OMG. I didn't even knew you could write that in C (and I have my name in the comp.lang.c FAQ...)

      Of course, I checked C99, and, no, you can't write that:

      3.6.6 Jump statements

      Syntax

                          jump-statement:
                                          goto identifier ;
                                          continue ;
                                          break ;
                                          return expression<opt> ;

      identifier being defined as:

      identifier:
                                          nondigit
                                          identifier nondigit
                                          identifier digit

      So, goto *f() is a no-no (as is probably &&a)

      But, anyway, wow. Gcc actually compiles that to something that somewhat runs...

    4. Re:Example by Anonymous Coward · · Score: 3, Informative

      Yes, it is non-standard. But quite useful for some things (although not in the way written above). Consider a function that needs to return and then resume where it left off the next time it is called. Could be done by wrapping it in a large switch, but this is more direct and efficient.

      #include

      void *f(void *p)
      {
              if(p != 0)
                      goto *p;
              return &

      a: printf("A\n");
              return &

      b: printf("B\n");
              return &

      c: printf("C\n");
              return &
      }

      int main(int ac, char **av)
      {
              void *p = f(0);

              p = f(p);
              p = f(p);
              p = f(p);
              p = f(f(f(f(p))));
              return 0;
      }

      [and perhaps it's time to get myself an account on here... captcha: "untested"]

    5. Re:Example by Anonymous Coward · · Score: 0

      Is that ever better than just creating a typed state variable?

      State f(State startState) {
      switch(startState) {
      case State_a:
      printf("A\n");
      return State_b;
      ...

    6. Re:Example by 7+digits · · Score: 2, Interesting

      I don't think the efficiency is worth having a non-standard construct, considering a simple switch would do the trick.

      You could also split the function in multiple function (because having all the code in the same function is not very useful as local variables are trashed between executions), and directly returning pointer to the next function to call (hence you could spare of the cost of actually calling f() before jumping).

      Anyway, a nice trick. Didn't thought I would learn another one in C. The worst I ever did with function pointer (not in production code, of course, just to provoke disgust) was in the line of:

      #include

      int f0()
      {
              return 10;
      }

      int f1()
      {
              return 20;
      }

      int f2()
      {
              return 40;
      }

      main()
      {
              printf( "%d\n", (*((int (*)())(((int)f0+(int)f2)/2)))() );
      }

      (yes, this will print 20 on most compilers).

    7. Re:Example by benjymous · · Score: 1

      using VS2005, that fails miserably in debug, but works fine in release.

      --
      Help me! I'm turning into a grapefruit!
    8. Re:Example by Anonymous Coward · · Score: 0

      Nifty code - lots of fun to read.

      Now I feel the need to overdose on something and end it all to get that code out of my short term memory. Good job.

    9. Re:Example by MikeBabcock · · Score: 1

      Or a local static?

      There's a reason I like Python ... it actually has this type of functionality built into the language.

      That aside, I think I last used something like this when I wanted that functionality in C:


      int foo()
      {
          static int i=1;

          switch (i)
          {
              case 1:
              i++;
              printf("First operation\n");
              return i;
          case 2:
              i++;
              printf("Second\n");
              return i;
          default:
              return -1;
          }
      }

      --
      - Michael T. Babcock (Yes, I blog)
    10. Re:Example by sxltrex · · Score: 2, Insightful

      I pity the developer who has to maintain your code after you've moved on.

    11. Re:Example by QuoteMstr · · Score: 1

      Labels as Values (i.e., "Computed Goto"). The OP's example is still illegal because he's jumping down the stack frame, but the syntax is fine for gcc.

    12. Re:Example by gknoy · · Score: 1

      Functions that resume where they left off ... wow. It makes me want to cuddle up in a corner with a nice cozy functional language and try to forget I read that completely. ;)

      I exaggerate ... but it pretty much seems to be comlpetely counter to functional programming principles. When would you consider it a good idea to use such a construction? Why would you want a function do that? What is the alternative, less-clever way of doing it?

    13. Re:Example by sjames · · Score: 1

      WOW! That's stunningly ugly yet it compiles with only a warning and actually runs as (mis)designed!

      If the cursed blink tag worked, i'd use it to put a blinking "never actually do this" tag in a red 100 point font on that code. That would be perhaps the first ever entirely justifiable use.

      Congratulations!!!

    14. Re:Example by Anonymous Coward · · Score: 0

      When would you consider it a good idea to use such a construction?

      It's a way of simulating coroutines. And there's nothing non-functional about coroutines.

    15. Re:Example by Anonymous Coward · · Score: 0

      Hans? Is that you?

    16. Re:Example by EvilBudMan · · Score: 1

      Sure, in assembler I believe it is JMP.

    17. Re:Example by Anonymous Coward · · Score: 0

      Erm... what problem is this supposed to solve? And why is this supposed to be the best solution?
      * Doesn't conform to the C99 standard. Check.
      * Is unreadable to most programmers. Check.
      * Does something that could easily be done in a different and more clear way. Check.
      * Has a reasonable completely different alternative interpretation. Check.
      All in all, I don't think that snippet is very good advertising for goto.

    18. Re:Example by volpe · · Score: 1

      a no-no (as is probably &&a)

      Definitely, "&&" (as a succession of unary operators, not logical AND) is never valid, since unary "&" takes an l-value and yields an r-value.

    19. Re:Example by dargaud · · Score: 1

      void *f() {...}

      I don't understand this declaration syntax. What does it do ? Also &&a where a is a label. I can understand &a being the address of the label, but I've never seen && anywhere.

      --
      Non-Linux Penguins ?
    20. Re:Example by Anonymous Coward · · Score: 0

      I'm appalled. But it's entertaining to see the behaviour change as you up the optimization on gcc. For me, the best behaviour occurs at -O3.

    21. Re:Example by clone53421 · · Score: 1

      void *f() {...}

      Declaration of a function which returns a void pointer.

      &&a

      This I'm not as confident of, but it appears it is the address of the address of the label. I.e. a pointer to the address of the label – which is exactly what you need, since you dereference the pointer and have the address of the label, which is what goto requires.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    22. Re:Example by Anonymous Coward · · Score: 0

      So, goto *f() is a no-no (as is probably &&a)

      Lets follow the citation about computed goto in C/C++ found in Wikipedia.

    23. Re:Example by 7+digits · · Score: 1

      Nope. The document you pointed to is about computed goto in *IBM*XL* C/C++

      In C99 goto *f() and &&a are both no-no.

  25. complex finance math by Anonymous Coward · · Score: 3, Funny

    I worked with some finance guy who was convinced that the square root of a negative number -x was -sqrt(x), and wouldn't hear otherwise. I hacked sqrt(x) to return sgn(x)*sqrt(fabs(x)), but he complained that when he squared the answer, he didn't get back a negative number. Luckily our code was C99 so I changed his dollar type to be "double complex", made him use the complex sqrt, and changed his print function to display creal(x) - cimag(x). The guy said things worked great. I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

    1. Re:complex finance math by Anonymous Coward · · Score: 0

      That'll be a problem if you ever have to handle extremally large transactions. Doubles round. Finance guys really hate it when their cents go missing.

    2. Re:complex finance math by Sique · · Score: 0

      It might have been some average distances on a random walk (for instance as a model for futural prices or interests). If you wait a time t, then the expected distance from your starting point in a Brownian random walk is ~sqrt(t). And if you look into the past, you might get imaginary expected distances :)

      --
      .sig: Sique *sigh*
    3. Re:complex finance math by X0563511 · · Score: 0

      The alternative to that dirty hack: finance guy takes remedial algebra

      --
      For large sets, this will be our guide even unto death, for the LORD will work for each type of data it is applied to...
    4. Re:complex finance math by Anonymous Coward · · Score: 0

      No, accountants hate it (think: bank accounts). If you're just modeling or estimating something something (i.e., what the financial institutions do), then doubles are OK.

    5. Re:complex finance math by Xenographic · · Score: 2, Funny

      > I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

      What? I'm sure most finance guys are adept enough at counting both real and imaginary dollars, so having complex dollars isn't really that complex...

    6. Re:complex finance math by EdgeyEdgey · · Score: 2, Insightful

      but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.

      They're called Imaginary dollars, and there's a lot of them about at the moment.

      --
      [Intentionally left blank]
    7. Re:complex finance math by san · · Score: 1

      That'll be a problem if you ever have to handle extremally large transactions. Doubles round. Finance guys really hate it when their cents go missing.

      Note that he's using doubles. 'Extremely large' here would be bigger than $10^15. If he's in Zimbabwe, or his company has transactions two orders of magnitude bigger than the GDP of the EU, there may be a few dollars lost in rounding. But anything less than that should be safe.

    8. Re:complex finance math by Rockoon · · Score: 1

      Remind me not to hire you for any floating point work.

      --
      "His name was James Damore."
    9. Re:complex finance math by san · · Score: 1

      If you're running one of the most popular distributed computing clients out there, you're actually running some of my floating point work, mr. Troll.

      If you'd looked at GPs post it'd be obvious that he's talking about taking square roots of dollar amounts, which no financial transaction software should ever do, so doubles are perfectly appropriate here, and probably overkill.

    10. Re:complex finance math by maxwell+demon · · Score: 1

      So now we know who's really responsible for the current financial crisis. :-)

      --
      The Tao of math: The numbers you can count are not the real numbers.
    11. Re:complex finance math by Bakkster · · Score: 2, Insightful

      I learned long ago that regular math and financial math follow very different rules.

      --
      Write your representatives! Repeal the 2nd Law of Thermodynamics!
    12. Re:complex finance math by janwedekind · · Score: 1

      Shouldn't be a problem as long as the bank has enough imaginary reserve funds to back it up.

    13. Re:complex finance math by Rockoon · · Score: 1

      Apparently your dumb ignorant ass missed the part where you overestimated the accuracy of doubles by two orders of magnitude.

      Here is a tip. When doing USD financial calculations, AT A MINIMUM you need to be accurate to the PENNY... and in fact the person you replied to even mentioned it ..

      I wasn't trolling.. I was observing your mistake.. Now I am observing your over-inflated ego and completely ignorant reluctance to find your error.

      I dont give a flying fuck what programs you have written in the past and it is clear to me that distributed computing clients do not expressly need accuracy, or apparently a programmer that is critical of his own kneeJERK bullshit.

      --
      "His name was James Damore."
    14. Re:complex finance math by san · · Score: 1

      You don't seem to understand the difference between financial modeling and financial transactions.

      Apparently your dumb ignorant ass missed the part where square roots of dollar amounts were taken, which clearly points towards some kind of random walk diffusional modeling which has nothing to do with financial transactions and pennies.

      If you would have been really clever, you would have noted that what he wanted (complex values for dollars) is mathematically the same as asking for imaginary negative time. The GGP should have been talking about logarithmic dollars to begin with to just avoid this whole issue. It's the only quantity where such quantities make sense.

      You're completely right, though, in asserting that distributed computing clients don't need numerical accuracy per se. Getting an estimate of the size of phase space is often more than enough - it's what makes simulation different from single-point energy evaluations, it's exactly what makes CPU time useful for scientific applications.

      I'd still advise anybody against working with you, or for you, for the sole reason that the pedantry you're bringing forward in your arguments would seem to make you a very poor manager of actual people. There's an aggression there that is simply not professional.

    15. Re:complex finance math by Rockoon · · Score: 1

      You were off on the accuracy by two orders of magnitude, and not on the conservative side either. Now you are making excuses for why that error didnt matter. Really?

      You were wrong. Its really that simple. It does not matter if the error matters or not. When errors like that do not matter, it is only through LUCK.

      --
      "His name was James Damore."
  26. yuck by Ben1220 · · Score: 1

    yuck yuck yuck keep these stories to yourselves, this is distressing me. If I knew software I was using was coding like this I would feel uncomfortable using it, even if it seemed to be working.

    1. Re:yuck by quintesse · · Score: 5, Insightful

      Basically ALL the software you use works like this.
      Welcome to the real world, no need to feel bad.

    2. Re:yuck by stevey · · Score: 1

      Never look at thedailywtf.com then!

    3. Re:yuck by Anonymous Coward · · Score: 0

      Just a minor correction: all *commercial* software works like this.

    4. Re:yuck by TheRaven64 · · Score: 2, Insightful

      What, you think no hobby programmers have added quick hacks because they've spent two days chasing a bug and still can't find it? No open source projects have ever added quick hacks to make a feature they want to boast about work in time for their code freeze?

      --
      I am TheRaven on Soylent News
    5. Re:yuck by Anonymous Coward · · Score: 0

      You haven't used Windows?

    6. Re:yuck by dkf · · Score: 1

      What, you think no hobby programmers have added quick hacks because they've spent two days chasing a bug and still can't find it? No open source projects have ever added quick hacks to make a feature they want to boast about work in time for their code freeze?

      You also get odd things hacked in where one project is being adjusted to work around a new strange feature added elsewhere by a completely different project.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    7. Re:yuck by deadkennedy · · Score: 1

      Agreed. There is no need to feel shame for getting something functional out the door.

  27. Who hasn't? by Opportunist · · Score: 4, Funny

    After years of programming, I guess everyone had to cut some corners sometimes. It's also not (always) a problem of goofing off, a module you depend on not shipping in time but you being required to keep your deadline can already force you into doing just that: Delivering a hack that 'kinda-sorta' works, or at least the customer won't notice 'til we can ship the patch.

    Yes, that happens often. It's dubbed "Bananaware". Delivered green and ripens with the customer.

    --
    We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
    1. Re:Who hasn't? by Anonymous Coward · · Score: 0

      So... If someone pays peanuts and get monkeys, they deliver bananaware?

      Where are my peanuts? BRB

    2. Re:Who hasn't? by TheSoepkip · · Score: 1

      Standard practice in the games industry ?

    3. Re:Who hasn't? by Opportunist · · Score: 1

      It's not standard practice in what industry? And don't quote medicine here, I've seen far too many medical appliances that crap out due to faulty software.

      --
      We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
  28. The solution is simple by Sparx139 · · Score: 1

    Swap to FOSS and change it yourself :p

    --
    Our culture doesn't get smarter, it just finds new ways of being retarded.
  29. Everyday by stimpleton · · Score: 1

    Have you ever needed to insert terrible code to make something work at the last minute?

    Jesus, every fucking day. Sole IT/Everything guy here.

    Yesterday it was enabling the personal IIS service on an XP desktop to get a demo going of an OCR scanner server for a board member meeting, because the scanner on loan would not talk to samba shares. Today I commented out some PHP code that read's a database for a web page and instead pasted in an excel page the admin girl had done. Next year that data will not update automaticaly. I will wait for the inquiry as to why and fix it then. Tomorrow i will FTP the javascript code snippet to our intranet web page that is IE 5.5+ only because thats our work environment....except for the graphics dept....but there is only 4 of them.

    For some people, the odd incident are cute, amusing anecdotes. For me, it is everyday in the trenches.

    --

    In post Patriot Act America, the library books scan you.
  30. PHP signed 32 bit integers by jesset77 · · Score: 1

    PHP signed 32 bit integers .. I really can't say much more without crying.

    I thought it was just wonky 64-bit support, until I found out their MAXINT was influenced by the machine the code ran on.

    I would write code to get around the apparently wonky support ("So you won't accept a 32 bit unsigned hex literal, eh? ok I'll add two of them together and comment why.. great, that passes all the unit tests..), little did I know that these things were being silently cast to 64 bit floats on the affected machines.

    It wasn't until an affected machine had to bit-mask numbers larger than ~2.14 billion that we began to notice the problems. It was an edge condition noone really forsaw, so no tests were written until it was too late. It took FOR EV UHHRR to track this sh1t down, given that it worked on 75% of the servers and 50% of the valid inputs!

    Our values were all meant to be 32 bit unsigned, so we eventually had to kludge something together that "utilized" the negative bit of PHP's prefered 32 bit signed values.

    Now, most of the sh1t works, but you can't sort the values out of the database easily without all the +2.14bil values preceding zero. (the database doesn't have this @#$% int problem..) We're still gritting our teeth waiting for the other shoe to drop.

    This is a "kludge" insofar as we need to abandon PHP as a lost cause, and lack the spare man hours for the effort. :(

    --
    People willing to trade their freedom of expression for temporary entertainment deserve neither and will lose both.
    1. Re:PHP signed 32 bit integers by El_Muerte_TDS · · Score: 1

      Your first mistake was not reading the PHP manual. As far as I can remember integers in PHP have always been signed. Not sure when this part was written in the manual but, but considering you are refering to the MAXINT constant it was probably there when you wrote the code:

      The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

      And after that:

      Integer overflow

      If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

      PHP has a lot of wonky behavior, but at least this is clearly documented.

    2. Re:PHP signed 32 bit integers by jesset77 · · Score: 2, Interesting

      Axually, we wrote the code long before 4.4.0 or 5.anything, so... new manual entry is unhelpful. :) (I cited "MAXINT" given my C heritage .. PHP's nomenclature fails anyway, as they lack an analogue to "MININT" ;3)

      When you've got code failing at unpredictable places for unpredictable reasons, the first place you look is not the "integer" subsection of the manual, anyhow. Besides, by that time the damage were already done. We noodled out the cause and thereafter found your cited manual points to corroborate our theory.

      We were still stuck using PHP which apparently cannot understand anything but signed 32 bit reliably, interfacing with MySQL which isn't capable of interim calculations in that space.

      we refuse to write anything but simple two's compliment logic into all of our applicable SQL statements, so for things like sort we just aren't going there.

      Allow me to forstall suggestions of using GMP given that gmp_strval(gmp_add(gmp_init("2"), gmp_init("2"))) is fail compared to "2+2" in every conceivable way, and there do not appear to be any OO bindings for GMP in PHP 5.x to rectify.

      Put simply, we could obviate this problem easily if ANY of the following were possible:

      * Sane integer support in PHP

      * Sane OO support in PHP (for example, OO GMP bindings .. though there would still be crippling performance hits for major parts of our app!)

      * sane functional support in the database to handle the two's compliment logic imposed by PHP

      If we had the resources to remake the project in Ruby or Python against a postgres database, then all of those possible solutions would be at our fingertips, so much so that only the first solution would need to apply. The other solutions/capabilities would simply stand around looking cool. :P

      So... meantime, can't afford the Ferrari and have to duct tape the pinto's engine together. *sob*

      --
      People willing to trade their freedom of expression for temporary entertainment deserve neither and will lose both.
    3. Re:PHP signed 32 bit integers by Anonymous Coward · · Score: 0

      If you're doing bitmasking that sounds like serious techy programming. So why don't you use a serious techy programming language?

    4. Re:PHP signed 32 bit integers by cheesybagel · · Score: 1

      FWIW IIRC Java doesn't allow unsigned integers either...

  31. Even worse stuff! by syousef · · Score: 4, Interesting

    Some of the worst I have seen:

    In critical C code:

    if (some condition)
            i *= 0;
    else
            i *= 1;

    And I was the actual variable name.

    Even worse, on a different project, an Easter egg that told the user their hard drive was about to be erased, and another that popped up about 30 dialog boxes full of banter between Spock and Kirk. Worst of all this code written in VB and was licensed for megabux then we got hold of it for orders of magnitude more megabux (Most of the original coders were hired fresh out of highschool). It ended up being rewritten (thankfully NOT by me) but we had to get the source to work out how it worked in the first place.

    I wish I was making this up.

    --
    These posts express my own personal views, not those of my employer
    1. Re:Even worse stuff! by Anonymous Coward · · Score: 0

      A decent compiler should optimise that easily. Not worth worrying about.
      The easter egg is worth disciplining the coders for though.

    2. Re:Even worse stuff! by robzy · · Score: 1

      It's not about optimisation, it's simply about future (or even current) programmers being able to understand the code. That code is not understandable.

    3. Re:Even worse stuff! by MadKeithV · · Score: 1

      And depending on the compiler and / or the type of i, might not even be half as trivial as it seems. Just imagine what you could do with an overloaded operator= ;-)

    4. Re:Even worse stuff! by Anonymous Coward · · Score: 2, Interesting

      I've come across horrible if-statements, too. One developer I worked with liked using the following for code he wasn't using right away: if (1 == 2). There're many other hilarious variations, of course. The thing that got me was nobody else on my team questioned that if-statement for over 4 months! They saw it and assumed it was important. I came across it while fixing a bug and, at first, couldn't see why several hundred lines of code seemed to do nothing at all. In the end, all code surrounded by that if-statement was unneeded, as admitted by the developer in question. Why didn't he remove all of it to make things clearer for the rest of us in the first place? Instead he let it sit there and clutter up pertinent code until another person took the time out of their busy schedule to do some housekeeping. Don't get me wrong; that developer had done the same sort of thing on many files - not only the specific instance mentioned here. Hunting through ~1100 files for rogue if-statements wasn't fun, even with aide of search functionality in SVN, since I 1) had no clue what other conditions the guy decided to use while being lazy and 2) couldn't figure out where to begin since the issue was EVERYWHERE. I made the developer sit down with me in order to make progress. When all was said and done, the code base was noticeably lighter and much more manageable. Oh, the joys of going through everybody else's code while fixing bugs. The biggest change came in the form of new and incredibly strict coding standards for the team. This was my first programming job and I'd only been there for 3 months, so I guess it was a good experience in one way or another.

    5. Re:Even worse stuff! by Anonymous Coward · · Score: 0

      I wrote code like this before:

      i*=int(some condition);

      But it was for performance. It removes the branching, so you get a lot of speedup if it is inside a loop.

    6. Re:Even worse stuff! by maxwell+demon · · Score: 1

      Given that the code snippet only used operator*=, an overloaded operator= would have had no effect at all. An overloaded operator*= on the other hand ... ... and of course, somewhere deeply hidden in a header, there might be something like

      #define i (*some_function(j,k))

      where of course j and k are to be provided by the code using the macro.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    7. Re:Even worse stuff! by Anonymous Coward · · Score: 0

      I'm not a programmer, but I found the following in a pretty critical app at a (at the time) Fortune 100 company while trying to figure out why certain company names were not coming up in a certain drop-down (okay, combo) box in a VB app (I know, critical app in VB?!).

      Somewhere in the code, the source for the combo box was c:\temp\filename.txt.

      The app (technically, a front-end for a commercial app) was written at high cost by a nationally known consulting company. Shortly thereafter, my company hired a dedicated developer to rewrite the whole system.

    8. Re:Even worse stuff! by DrinkDr.Pepper · · Score: 1

      What's wrong with that?

      At least it wasn't:
      if (some condition)
      i /= 0;
      else
      i /= 1;

      --
      0xfeedface
    9. Re:Even worse stuff! by syousef · · Score: 1

      It's not about optimisation, it's simply about future (or even current) programmers being able to understand the code. That code is not understandable.

      Bingo. If I were hiring you'd still be on the short list.

      For a programmer to write such code and yet be able to make it work the only thing I can think of is that they were bored and somehow thought that it would be appropriate to waste everyone's time trying to decipher his nonsense. It's pure vandalism. If it's critical code that hasn't been touched for some time the regression testing to ensure nothing else breaks when removing this can be prohibitive. I can only hope the fool that responded "don't worry let the compiler optimise it" was trolling.

      --
      These posts express my own personal views, not those of my employer
    10. Re:Even worse stuff! by Anonymous Coward · · Score: 0

      if (some condition)
                      i *= 0;
      else
                      i *= 1;

      An optimizing compiler should fix that, but I'd be more worried about checking other things that that same programmer had changed.

      My dirty story is one time when I was getting prepped for a demo to military brass (of a late software project that was in deep doo-doo), I realized I needed to change some text strings in a large Ada program. Rather than change the source and recompile, which would have taken a long time, I edited the binary with Emacs 18. I then started the demo and left it running ... Some days later when it was time to give the demo, the local bosses decided to just leave it running (it was showing uptime and processing statistics and the numbers were impressive by that point) so I did. And the first (and so far only) demo I've ever given to a multi-star General in the US Army was done with a binary edited in Emacs.

    11. Re:Even worse stuff! by SL+Baur · · Score: 1

      One developer I worked with liked using the following for code he wasn't using right away: if (1 == 2).

      Don't judge him too harshly. It was possible in early FORTRAN implementations to do `1 = 2' and thus modify a constant making the constant `1' in the source code `2' in the running code. It was a bit more complicated than that, but that was the effect. As I recall, though I can't find it now, people did that to fix last minute bugs when certain "constants" needed to be changed.

      http://www.ibiblio.org/pub/languages/fortran/ch1-8.html

    12. Re:Even worse stuff! by gcobb · · Score: 1

      If I still had some mod points I would have given you +1 Funny! Just in case someone else sees this and doesn't get the joke: turning a "condition" into a 0 or 1 (for the multiplication) involves at least as much branching (in the assembler code) as having written:

      if (! some condition) i=0;

      in the first place!

    13. Re:Even worse stuff! by clone53421 · · Score: 1

      I assume you think "condition" can be (0, !0)? If it's a bool, there are exactly two values it can have: (0, 1). Creating an int from those is trivial.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    14. Re:Even worse stuff! by gcobb · · Score: 1

      It says "some condition" so I am assuming it is a conditional expression, must likely a comparison test (e.g. ab). Converting the result of a comparison to an int requires a conditional jump. Exactly the same conditional jump that is required for an if! If it was a boolean I am assuming the poster would have said "some boolean".

    15. Re:Even worse stuff! by gcobb · · Score: 1

      (e.g. ab)

      Oops. Meant to say: a<b

    16. Re:Even worse stuff! by clone53421 · · Score: 1

      Depending on how the compiler optimizes it, I suppose. It could basically be reduced to something like,

      CMP a,b
      JGE endif
      MOV i,0
      endif:

      ...but if the compiler is creating a bool on the stack frame as temporary storage, well, it all depends.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    17. Re:Even worse stuff! by Anonymous Coward · · Score: 0

      I can only hope the fool that responded "don't worry let the compiler optimise it" was trolling.

      Or that you neglected to mention what the actual problem with the code. Under various assumptions (no operator overloading, no integer overflow, no conversion operators, i not being volatile) that code is equivalent to "if (some condition) i = 0;" and a decent compiler would do that. I would look at the generated assembly to check. If "i" was an index to a short loop variable in local scope that would even be a reasonable name.

      If the code has been changed from descriptive code into less descriptive code you should have mentioned that. And *any* changes (especially to critical code) would need regression testing - any recompile introduces risk (e.g. of uncovering a dormant bug that was based on memory alignment, or of a bug in the compilers optimiser).

    18. Re:Even worse stuff! by syousef · · Score: 1

      Or that you neglected to mention what the actual problem with the code. Under various assumptions (no operator overloading, no integer overflow, no conversion operators,

      Operator overloading in C? I think you need to get a clue what you're talking about. Not every language is object oriented.

      --
      These posts express my own personal views, not those of my employer
  32. Prolog Assignment by becker · · Score: 4, Interesting

    That's completely understandable in this case of programming in Prolog.

    Prolog is a declarative language.

    You declare the rules, and the system figures out a result that matches those rules.

    The problem is that this basically doesn't work. So a Prolog programmer has to write the "declarative" rules in a procedural order so that the run-time system doesn't have to try every possible combination to find (or fail to find) a matching result.

    The proper ordering of declarations can be quite subtle. With a modestly complex program you can make a seemingly unimportant change in the order of the declarations and have the runtime go from a second to a week.

    In this case the professor didn't (couldn't) know how long a Prolog program to solve this problem should take. He just assumed that you had found a more efficient ordering for the declarations. He might even have thought it was luck rather than deep insight that your program was faster than his. But you have to a decent understanding of the limits of Prolog to get a complex program to complete in a reasonable time, so you had to be good before you could get that lucky.

    If you couldn't already tell, I have a low opinion of Prolog and declarative languages. They are "parlor tricks". Much like computer 'Life' and neural networks, simple programs can produce unexpected seemingly-sophisticated results. But they don't get better from those initial results. To compute the answers or results you want in a reasonable time, you end up with at least the complexity of writing things in the traditional explicitly procedural method.

    The promoters of declarative language typically don't mention that you end up writing rules in an explicitly procedural order if you want the program to work. If you press them on the issue, they then say "well, OK, it's not actually any easier to write, but it's easier to verify that you've correctly specified the desired result." But if you have to carefully shuffle declarations around, and even then some results unpredictably take centuries to compute, pretty much no one cares.

    1. Re:Prolog Assignment by EMN13 · · Score: 1

      Ah, so Prolog is kind of like most modern Regex engines?

    2. Re:Prolog Assignment by GargamelSpaceman · · Score: 1

      Mozart Oz. You only have to think about the subtle crap if you're actually using it.

      --
      ...
    3. Re:Prolog Assignment by eison · · Score: 1, Informative

      You know, SQL is declarative, and definitely one of the most powerful and useful programming languages available today. I suggest refining your opinion to hate languages that try to make entire problems declarative rather than limiting themselves to appropriate pieces, such as data querying.

      --
      is competition good, or is duplication of effort bad?
    4. Re:Prolog Assignment by QuoteMstr · · Score: 3, Informative

      General-purpose declarative languages are bunk, I agree.

      However, domain-specific declarative languages often work pretty well. Consider build systems (Make, ant, etc.), or SQL, both of which are declarative.

    5. Re:Prolog Assignment by greed · · Score: 2, Interesting

      Interestingly, a LOT of people, let's say almost everyone, get Make wrong because they don't understand how the declarative rule structure works.

      I'm not a fan of ANT, actually; I think it exists to solve a problem that Sun should have never created in the first place. (Produce arbitrarily named .class files from a given .java file.) I don't know how declarative it _really_ is under the covers, but everyone I see saying "it's better than make" are doing procedural things with it and using that to justify ANT over make.

      (My gripe with ANT--aside from the XML soup--is it affords sloppy build systems: it's a wildcard enabler.)

    6. Re:Prolog Assignment by Blakey+Rat · · Score: 2, Insightful

      Yeah, but everybody's experienced the SQL query which, when re-written to say the same thing a different way (i.e. replacing a sub-query with a join) runs 10 times faster than before. The trick to get good at SQL is just to remember these cases and avoid them... the fact that the SQL parser/engine can't do this optimization on its own doesn't speak well for SQL's design.

      It also doesn't help that when extensions are made to SQL (like T-SQL), the very first thing they add are procedural looping operators.

      That's not to say the *concept* of SQL is flawed, just that the language itself is, IMO.

    7. Re:Prolog Assignment by Abcd1234 · · Score: 2, Informative

      If you couldn't already tell, I have a low opinion of Prolog and declarative languages.

      Better not tell your database, it might get offended...

  33. I knew a guy who pulled a hack like this by FranTaylor · · Score: 2

    it made a total hash out of what I was trying to do. But he lost the source code, so I couldn't prove that he did it. Of course we couldn't fix it either. It was in code that calculated people's paychecks. He got fired. I quit.

  34. Only works on GCC by Viol8 · · Score: 1

    Taking the address of a label is a gnu extension to C. Its not part of the standard language.

    1. Re:Only works on GCC by sugarmotor · · Score: 1

      $ cat m.c
      #include

      void *f(void)
      {
      a:
              printf("Here!\n");
              return &
      }

      int main(int ac, char **av)
      {
              goto *f();
              printf("There\n");
              return 0;
      }
      $ gcc -std=gnu99 m.c
      m.c: In function âfâ(TM):
      m.c:7: warning: function returns address of local variable
      $ ./a.out
      Here!
      Here!
      $ uname -a
      Linux myosin 2.6.24-19-generic #1 SMP Wed Aug 20 22:56:21 UTC 2008 i686 GNU/Linux
      $ gcc -v
      Using built-in specs.
      Target: i486-linux-gnu
      Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.2 --program-suffix=-4.2 --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --enable-targets=all --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
      Thread model: posix
      gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)

      Use a different -std switch?

      Stephan

      --
      http://stephan.sugarmotor.org
    2. Re:Only works on GCC by Viol8 · · Score: 1

      Sorry , whats your point? You compiled it with gcc, of course it'll work. Try compiling it with Suns forte compiler for example and see what happens.

    3. Re:Only works on GCC by sugarmotor · · Score: 1

      Sorry, the point was that gcc issues a warning:

      m.c:7: warning: function returns address of local variable

      Stephan

      --
      http://stephan.sugarmotor.org
  35. First casualty of last minute coding - structure by Viol8 · · Score: 1

    If you've found your code has a last minute bug or god forbid a design flaw then all those nice class/flow/structure diagrams go out the window and its quick and dirty hack time. Unfortunately this happens far to often meaning even the most well controlled projects eventually end up with some hairball code that some poor maintenance coder gets to wrestle with 2 years down the line. After all - if the hack works who's going to bother to tidy it up and rewrite it especially if everyone haa another dozen tasks on their todo list.

  36. Yes.. it was called PHP. by Anonymous Coward · · Score: 0

    ?php .... nuff' said. :-)

  37. Wow am I the only one in here by Big+Hairy+Ian · · Score: 3, Insightful

    who just aims to get what is functionally absolutely needed finished & tested by the deadline? Bear in mind that most of my deadlines get set by clueless salesmen who even if they consult me generally tend to ignore what I say and tell the client what the client wants to hear.
    I haven't implemented a fully finished system by the deadline in years simply because I can't squeeze 3 months work into 1 month.

    --

    Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.

    1. Re:Wow am I the only one in here by wrook · · Score: 2, Interesting

      Here is my strategy for dealing with this situation:

      1) Tell the salesmen that you have absolutely no problem with them telling the customer whatever they want. Their function is to make sales to customers. Your function is to write software. You won't try to tell them how to do their job, because quite frankly you aren't qualified to know what's best for sales. Of course the implication is that they shouldn't tell you how to write software, but you probably don't have to tell them this explicitly (well, it happened once that I had to say it...)

      2) Show the salesman what you actually *are* going to deliver. Generally a list of use-oriented functionality is the best. You might be doing a lot of refactoring underneath, but they won't understand that. Only list what the user will see.

      3) Probably what they are saying to the customer and what you are promising to deliver will not match. No matter how clueless they are, the salesmen will probably notice and tell you, "You had better do something to fix the situation". This is where you reiterate, "I can't tell you what to say to the customers, that's up to you. But this is what I plan to release. However, if you would like to substitute something on this list with something more important, I'd be happy to oblige."

      4) Now they will still want it all. They will tell you that the whole company will go under unless you deliver everything. You can now say, "That's a shame. I like working here too. Well, if that's the way it is, I guess I'll go fix up my resume. It was great working with you." You only have to do this once (thank god). At this point the salespeople will say, "Well, maybe we can do something if you at least give us feature X".

      5) Negotiate with the salespeople. But use each piece of functionality as a lego block. Its size is immutable, but you can put it in, take it out, put it in a different place etc. At every point make sure to point out that you are quite happy to allow the salesmen to choose what they want you to do. It's just that it doesn't all fit.

      6) Sometimes you will run into the situation where the salesman will swear at you and tell you to go do something anatomically impossible. Then they will storm off. At this point it's important to let them go, but to go to your own management (or executive management if you have no manager) and explain, "The salesmen are upset and I understand their point of view. They can't have everything that they want. It's frustrating for me too. But I need them to choose what things are most important. If you could just have a chat with them so I can prioritize things properly I would really appreciate it." After this you will have no problems (unless the salesman in question *is* executive management, in which case you should jump ship as quickly as possible).

      7) Probably you will have to go through this charade about 4 or 5 times. But each time it will get easier. There will be one last time where they will pull every dirty trick in the book. Just hang tough, because after that you will have no problems.

      Hope this helps.

    2. Re:Wow am I the only one in here by Big+Hairy+Ian · · Score: 1

      Thanks for the info. I actually got out of most of this cycle (All the systems were basically in ways very similar and in other ways radically different) by developing my own IDE (Which took a long time but work here varies seasonally) which for the majority (99.5%) of systems got dev times down from months to hours sadly that's just made the salesmen expect instant turn around which I have to keep pointing out if it won't fit in my IDE we are back to 3 months which they find hard to swallow.

      --

      Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.

  38. Dirty web development by Rhaban · · Score: 1

    I work as a web developper, and I had a project based on a cms (joomla). the project had a very little budget and made use of several publicly available extensions that ran unmodified.
    The client asked for a last minute change, putting in the top of the page a form submit button that was in the bottom, and my boss told him we would do it, as it seemed trivial.
    We looked at the code for this particular extension, and it was the worst code I had ever read. It had no understandable structure, and modifying this particular extension to display the submit button before the other fields.
    modifying the css to display the button on top broke several other pages of the site, so I did the only thing that i could to move this button in less than 5 minutes: a little javascript that took the html of the button after the page loaded and put it where the client wanted it to be.

    1. Re:Dirty web development by mgblst · · Score: 1

      I had a customer who wanted to have the scrollbar on the top of the display box, rather than the bottom. A rather simple fix, sure, no problem. Except it can't be done, there is not easy way to do this. I had to implement my own scroll using CSS and javascript, an absolutely horrible hack.

      But it is what they wanted, and they were happy.

  39. Someone /has/ to mention Mel... by roderik · · Score: 1
  40. Funny story.. by MaGGuN · · Score: 0
    I once had to quickly come up with a story about inserting dirty coding tricks to make a deadline. And it had nothing to do with karma. The story goes like this:

    It was a very rainy day, both outside and inside, my deadline was comming up fast. My collegue asked if I wanted some coffee before I pull an all nighter, I told him to shut his pie hole... he is kinda annoying, but I might have been stressed. My job was to code and maintain the software for a secret amusement park on the island of Isla Nublar. After many arguments with my boss over sallary and what not, I got fed up, he never appreciated what I did for them, debugging and maintaining millions of lines of computer code. How many others can do that, am I right? Because of that, and greed, I made a sweet deal with another company involving some silly embryos, they paid alot up front!! :):) So I quickly hade to insert some dirty code to shut down the security system so I could get the embryos and stop others from accessing the system I had set up. One dirty thing I did was this: if ( user_session_admincommand_count == 3 && !magic_word) { StartPermissonDeniedSequence(); } . I am happy to say, I got away before they discovered what I had done. I ran into some other problems, but it had nothing to do with my code!! And hey, it was unix!!

  41. Velcro Sneaks Live by argent · · Score: 1

    I suspect that the "velcro sneaks" sticky walls problem survived at last until Havok 4, or it got recreated there, but it never got discovered because professional game developers just make sure that sticky walls never happen.

    But what happens when you've got thousands of people building game geometry who aren't professional game developers?

    Second Life had some horrible "Sticky Walls" problems after they upgraded to Havok 4. I wonder what Linden Lab did to fix them?

  42. Customers by CarpetShark · · Score: 2, Insightful

    Have you ever needed to insert terrible code to make something work at the last minute?

    Yes. But mostly it's not to "make it work"; it's because the customer wants something that is entirely against the original design they asked for.

  43. Last one was great! by amn108 · · Score: 1

    Hilarious read. Especially the last one, where the seasoned coder invites the younger one to his office and shows him the code line where he pre-allocated 2Mb of memory, so that he can remove it when the project is due shipping after memory constraints are check. I would say this kind of practice will do good on any project from text editors to NASA computer controllers. People respond very well to harsh reality, even if this reality is a bit "fake". Cut down on perceived memory and slow down (intentionally) the CPU, and give them a go at programming. After they are done with polishing code enough so that it runs at decent performance, remove the constraints and see it fly! This is especially good practice for Microsoft, with their ever increasing system requirements and not increasing functionality.

    1. Re:Last one was great! by QuoteMstr · · Score: 2, Interesting

      We do this at my job. We have a decent production database system, but we develop against a K6-2/400 with 256MB of RAM and a couple flaky SCSI disks. If it performs adequately there, it'll perform adequately anywhere.

    2. Re:Last one was great! by DRAGONWEEZEL · · Score: 1

      /agree.

      I thought that should be standard practice! It's a neat Idea, and reminds me of a story I read here I think where someone got their program ready to demo, and the lead dev put in a Do_Nothing loop, much to the programers dismay and slowing the app down a ton. Then when they demoed it, everything worked, and they shippped it. Later on the client complained of poor performance, and they issued an update right away...

      Also the framerate one, "You Wouldn't Like Me When I'm Angry", really made me chuckle. You can't do it all, and sometimes, you need others to understand whats acceptable in REAL TIME!

      For those who didn't RTFA:

      The solution took maybe an hour. A fellow programmer took four pictures of my face -- one really happy, one normal, one a bit angry, and one where I am pulling my hair out. I put this image in the corner of the screen, and it was linked to the frame rate. If the game ran at over 30fps, I was really happy, if it ran below 20, I was angry.

      After this change, the whole FPS issue transformed from, "Ah, the programmers will fix it." to, "Hmm, if I put this model in, Nick is going to be angry! I'd better optimize this a little first." People could instantly see if a change they made had an impact on the frame rate, and we ended up shipping the game at 30fps.

      - Nick Waanders

      --
      How much is your data worth? Back it up now.
    3. Re:Last one was great! by Pranadevil2k · · Score: 1

      The programming equivalent of training with wrist/ankle weights?

  44. Yep, The Best! by Anonymous Coward · · Score: 1, Funny

    I had a project which was built on a really old CMS that was badly written, we had extended it and hacked it to bits so many times it just wasnt funny.

    We had an error somewhere in the code, but couldnt for the life of us figure out where, eventually I resorted to this:

    1. Re:Yep, The Best! by ChienAndalu · · Score: 1

      Not shipping?

    2. Re:Yep, The Best! by geminidomino · · Score: 1

      Slashdot seems to have eaten your solu... OHHHHHHH...

      I c wut u did thar. ;)

  45. char Str[255] by dargaud · · Score: 2, Informative

    My worst shortcut is to use fixed-sized strings with non size limiting functions, as in:
    char Str[255];
    sprintf(Str, "%s, %s", Lastname, FirstName);
    I really wish snprintf was available on my C implementation.

    --
    Non-Linux Penguins ?
    1. Re:char Str[255] by Anonymous Coward · · Score: 0

      I sure you're doing something like

      if (strlen(Lastname) > 126) LastName[126] = 0;
      if (strlen(FirstName) > 126) FirstName[126] = 0;

      The sum of the lengths of the two names in your example cannot be more than 252 characters (255 - terminating null - comma - space). Otherwise, if those aren't fixed buffers as well where the user input is sanitized prior to being copied into, then you have a security hole (a sufficiently long enough first name and last name will allow an attacker to start writing directly into the stack meaning they can overwrite the return address of the function and take over your program).

    2. Re:char Str[255] by GreatBunzinni · · Score: 0

      Wasn't strlen() available? The following code would tell you how much memory you needed to hold that string:

      char *Str;
      size_t length;

      length = strlen(Lastname) + 2 + strlen(FirstName) + 1;
      Str = malloc(sizeof(char)*length);
      snprintf(Str,"%s, %s",Lastname, FirstName)

      --
      Slashdot, fix your code or at least hire someone who is competent at it to do it for you.
    3. Re:char Str[255] by dkleinsc · · Score: 4, Insightful

      I believe another name for that little snippet is "buffer overflow vulnerability".

      --
      I am officially gone from /. Long live http://www.soylentnews.com/
    4. Re:char Str[255] by TheRaven64 · · Score: 1

      Why don't you just add snprintf()? Grab the copy from OpenBSD libc and include it in your project. Mind you, for this kind of thing asprintf() is probably better...

      --
      I am TheRaven on Soylent News
    5. Re:char Str[255] by Sauron · · Score: 1

      I realise you probably can't use this trick, but I ran into some of the same issue when building my own functions that used varargs... How to allocate enough space for the return buffer w/o knowing how much space you'd need....

      Luckily, you can pass a size to vsnprintf(), and it will return the number of bytes needed if it's more than 'size':

      void sys_log (bool s_time, Log_Type type, Log_Level lev, char *fmt, ...) {
          char buf1[2];
          char *buf;
          va_list args;

          va_start (args, fmt);
          num = vsnprintf (buf1, 1, fmt, args);
          buf = malloc (num + 2);
          vsnprintf (buf, num + 1, fmt, args);
          va_end (args); ...
      }

      --
      I never claimed to be human.
    6. Re:char Str[255] by TemporalBeing · · Score: 1
      The simple answer is:

      size_t writtenCount = 0;
      // ", " + NULL terminator
      size_t lenLastName = strlen(LastName);
      size_t lenFirstName = strlen(FirstName);
      size_t bufferSize = 3 + lenLastName + lenFirstName;
      char* buffer = calloc(sizeof(char)*bufferSize);
      if (buffer != NULL)
      {
      writtenCount = sprintf(buffer, "%*s, %*s", lenLastName, LastName, lenFirstName, FirstName);
      }

      writtenCount should match strlen(buffer), which should match (bufferSize-1). The "%*s" guarantees that only that number of characters will at most be written for that string - you could also specify a specific width too I think. Any how, that gives you far better predictability of the output string since you know 100% for sure what the input will be.

      And if strlen() wasn't available - you can implement it yourself:

      size_t strlen(char* _someString)
      {
      size_t length = 0;
      char* strCharacter = _someString;
      while (strCharacter != NULL) length++;
      return length;
      }

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    7. Re:char Str[255] by TemporalBeing · · Score: 1

      If 'snprintf()' wasn't available, what makes you think that 'vsnprintf()' would have been?

      --
      Truth is like the sun. You can shut it out for a time, but it ain't goin' away. - Elvis Presley (source: imdb.com)
    8. Re:char Str[255] by naturaverl · · Score: 1

      Why don't you just implement snprintf? And name it my_fucking_snprintf()

    9. Re:char Str[255] by Anonymous Coward · · Score: 0

      You could at least do:

      char str[MaxName + 1 + MaxName + 1];

      sprintf(buf, "%.*s %.*s", MaxName, lastName, MaxName, firstName);

    10. Re:char Str[255] by cbhacking · · Score: 1

      I really wish snprintf was available on my C implementation.

      Leaving aside the question of what implementation of C *doesn't* have the safer string functions, there are a still lots of better ways to do that.

      For starters, you could implement your own snprintf(). It's not a trivial function, but if you use it that much... if your library is LGPL-compatible, you could also use the implementation in glibc.
      Alternatively, if you have the other safe string functions, such as strncat(), you could use them. It's a couple extra lines of code, but I'm pretty sure it actually takes less time to execute if you're worried about that.
      Finally, you could just bounds-check the arguments, using strlen() or similar.

      I relaize this is a story about the terrible hacks we've all used from time to time, but please, there's no valid excuse for trivially-exploitable buffer overflow vulnerabilities.

      --
      There's no place I could be, since I've found Serenity...
    11. Re:char Str[255] by SL+Baur · · Score: 1

      I really wish snprintf was available on my C implementation.

      You still have %*.*s, just pick 125 for all of them and you won't overflow. What kind of person has (or has parents who would give him) a name Christian or family longer than that?

    12. Re:char Str[255] by dargaud · · Score: 1
      I know there were several good suggestions to fix up my 'laziness', but here's why I haven't done it so far:
      • Deadlines zooming past, certainly no time to reimplement the wheel.
      • Use of variable format strings which precludes bound checking the arguments.
      • Portability: this current code has to work on Windows, Linux and embedded Linux; so grabbing the 1st snprintf source found on the net may not work.
      • Upgradability: the compiler makers have promised snprintf will be in the next version, so I don't feel like wasting my time right now only to reverse it later.
      --
      Non-Linux Penguins ?
    13. Re:char Str[255] by julesh · · Score: 1

      I really wish snprintf was available on my C implementation.

      What platform are you working on that doesn't have snprintf or an equivalent?

    14. Re:char Str[255] by dargaud · · Score: 1

      That's LabWindows/CVI for Windows/Linux. Next version should be C99 compliant. Current version is only partial and I have to use the previous one.

      --
      Non-Linux Penguins ?
  46. New London Underground station??? by Anonymous Coward · · Score: 2, Funny

    First year at university, as part of the end of year project, we coded a shortest path algorithm to work out the distance between two stations in the London Underground system. However at 4am a couple of hours before the class presentation we discovered a bug! This was that if you chose the station 'Bank' it could for example take you to 'Embankment' (since it contains 'bank'). Our 'fix'?? We renamed Embankment to... Embonkment! Nobody realised in the presentation! :)

  47. Configurable sleep() by Get+Behind+the+Mule · · Score: 2, Interesting

    So we had a race condition on database transactions using two-phase commit, your usual mind-fucking WTF situation, drove us up the walls for days, you all know what I mean. We knew it was a race condition because if we put a sleep() statement at the end of one of the transactions, everything ran fine. sleep(10) was always long enough, and since all of this ran asynchronously in the back end, an end user would never notice the difference.

    So we went to the customer. We told them that we could continue to bust our brains trying to find a "real" fix, and didn't know how long that would take, or we could just leave the sleep() in. And we could even make the length of the sleep interval configurable, so they could try to make it shorter than 10 seconds, if they really felt like fiddling around with it.

    The customer went for the configurable sleep().

  48. DOS to the rescue... by Xenographic · · Score: 2, Interesting

    > Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...

    I once did almost the same thing, except that I wrote the entire assignment the first day we got it, during class. But I couldn't turn it in yet. And nearly forgot about it. So I turned it in at the last minute...

    Except that I had misread the specification! Oh, the program worked just fine, but it printed everything to the screen. It was *supposed* to go to output.txt. That would've been trivial to change, if I actually had any time. But now I was out of time and couldn't change the code I had submitted...

    With a bit of quick thinking, I actually managed to convince the TA that the problem was that you were supposed to execute the program as:
    java MyProg > output.txt

    So instead of getting a zero, I got 98%, because I had failed to document this.

    1. Re:DOS to the rescue... by Philip_the_physicist · · Score: 1

      This is where Runtime.exec() comes in very handy.

    2. Re:DOS to the rescue... by PeterM+from+Berkeley · · Score: 1

      If I'd been the TA, I would have given you 98% too despite your misreading of the spec, even without your "fix". Come on, a 0 for getting it 98% right? With a trivial fix?

      Overly rigid grading encourages cheating, I would think. Imagine the pressure on people if it's all or nothing, 0 or perfect. You get no credit for learning anything unless you get the answer "exactly right" by the professor's definition of "exactly right"? Yeah, I can see people cheating like mad under such circumstances.

      The measure in a class should be, "How well have you learned the lesson intended, as demonstrated by your program?"

    3. Re:DOS to the rescue... by JohnnyComeLately · · Score: 1

      That's funny. You're story is my favorite out of all the comments here. Sometimes TAs can be unintended sources of humor.

    4. Re:DOS to the rescue... by Xenographic · · Score: 1

      To be fair to the TA, I believe we were allowed to tell them how to build & execute the program.

      Mind you, these were incredibly simple Java programs, so 99% of them would have been something on the order of:

      javac Prog.java
      java Prog

      There was no need for anything more complex than that, unless you had to pull a fast one like I did. Fortunately, the point of that assignment wasn't to learn about file I/O (we'd already done that), so I don't think they cared too much, and I'm not really sure if they knew what I was doing or not.

  49. Re:One word.. J... by MessyBlob · · Score: 1

    Most code gets assembled into GOTOs (jumps) anyway. I'm sure some competent programmers can manage their own GOTOs just like a compiler can.

  50. syntactic sugar by sigxcpu · · Score: 2, Funny

    syntactic sugar is just fine, but what I would really like is syntactic caffeine.

    --
    As of Postgres v6.2, time travel is no longer supported.
  51. VB6: Lost source code - Ultimate repack by netsavior · · Score: 5, Interesting

    So it was 1999 and I was working for a mom and pop software shop, we had been acquired by a dot com. All our money and toilet paper stock options were held until we delivered the re-branded product with source. Part of the "rules" said we had to have only C/C++ and VB6 source, NO OTHER LANGUAGE.

    . We finished converting a few rogue scripting modules and things like that, which creep in over time. But we COULD NOT find the source code to one of our VB6 DLLs (an old one that had not been changed since it was first compiled in VB6). We searched and searched and eventually the fastest coder(not me) started rewriting it. We were 1 day from delivery date and there was no way he could finish it, so I ran it through a disassembler.

    the C++ code we delivered looked like this:

    int functionName(int parm) {
    _asm {
    push esi
    mov esi, dword ptr ds:[esp+8]
    mov dword ptr ds:[edi], esi
    retn
    }
    ....(you get the idea)
    It was unreadable, but it compiled and worked and we got our money. I still wonder what they ever did with that... since the software is still in use...

    1. Re:VB6: Lost source code - Ultimate repack by mrwolf007 · · Score: 5, Funny

      Yeah, just think what those guys thought when they saw the code.
      "Wow, assembler code."
      "It must be highly optimized."
      "Told you it was a good idea to buy it."

  52. Not exactly programming, but... by TheFourthDoctor · · Score: 2, Interesting

    One of my uni courses our assignments required us to build circuits on breadboards in class - no opportunity to work on it otherwise. My lab partner and I were having problems with one assignment which, despite being wired properly, refused to produce the required output. After checking and rechecking wires, swapping out gates, etc., we were finally down to the last five minutes of class with no idea what to do next. Out of frustration, my partner reach out and scrunched the entire mess of wires in his fists and held them there.

    "Try it now"

    It worked. He just sat there while I dragged the prof over to evaluate it. As soon as he was done, my partner let go and it stopped working again.

    1. Re:Not exactly programming, but... by Anonymous Coward · · Score: 0

      If you guys were using a solderless breadboard, those things are notorious for making poor contact with inserted wires, especially if they've been in use for a while. Your partner's solution was the correct one.

    2. Re:Not exactly programming, but... by kisielk · · Score: 1

      Reminds me of my senior engineering project which we presented at a highly competitive national conference here in Canada. On the day the judges were coming around to the booths, our device suddenly stopped working. It was still connected to the computer through USB, but for some reason the analog-digital conversion was failing. Literally 10 seconds before the judges appeared in front of our booth my partner whacked the device enclosure with his fist and suddenly everything worked again. We ended up coming in 3rd :)

    3. Re:Not exactly programming, but... by techess · · Score: 1

      The wonders of "percussive maintenance". It is amazing how many things can be fixed with a good thwack.

      --
      Don't anthropomorphize computers. They *hate* that.
  53. Windows size by DarkArctic · · Score: 1

    A friend and I were writing a program for our semester long college project. It was supposed to be a file manager that worked on both Linux and Windows. The night before our presentation, I found that in Linux wxWidgets had a bug where widgets wouldn't automatically resize when the window did. The quick and dirty fix was to lock the window size when running in Linux and only demonstrate window resizing while running in Windows.

  54. Re:One word.. J... by MrPhilby · · Score: 1

    There is an assumption that code is always meant for humans to read.

  55. Easter egg dependency by plover · · Score: 4, Interesting

    We had an easter egg in our code that was in a routine scheduled to be executed only at 0-dark-30 when our users were long gone. But someone later called the routine as part of the loading process, and the users ended up seeing it anyway as they signed on at start of day. It made people smile, so we left it in.

    A few years later, we were telling a client that we couldn't add their new feature X because we don't have the memory. At that point the director said to get rid of the easter egg and then it'd fit. (A few hundred bytes was not going to make a difference, but our director didn't care, it was a perception thing.) What we got instead was a hundred bug reports that the easter egg wasn't displaying, and that they "needed" to see it so they'd know when start of day was complete.

    --
    John
  56. yawn! obviously not an embedded programmer by petes_PoV · · Score: 1
    Recite the mantra "gotos are bad" without even knowing the background - or the limitations of why so many people parrot this unenlightened and frankly ignorant diktat.

    When you're writing code for embedded microprocessors, there is no nice, warm, run-time environment. When your code gets to the end of main() what does it do? It certainly doesn't return to the operating system (what operating system? there is NONE, just the code you write, yourself) with an error or success value. it just carries on, executing whatever random noise was left in the eprom from it's manufacture.

    Under these circumstances, having a GOTO is not merely permissable, it's pretty much mandatory to get back to the beginning of your execution again. If you have been so brainwashed that your fingers are physically (apologies to people without fingers, please excuse the insensitivity) incapable of typing those 4 letters you can use other constructs, such as while(1) {... } but the effect is the same and may even create the same code. So don't kid yourself that GOTOs are bad, or even that they don't exist. They are one of the world's most useful, misunderstood and maligned instructions that EVERY processor has.

    Learn to love them and make it a personal goal to write at least one GOTO loop a day

    --
    politicians are like babies' nappies: they should both be changed regularly and for the same reasons
    1. Re:yawn! obviously not an embedded programmer by Wildclaw · · Score: 1

      Basically, what you are saying is that programming in inadequate primitive languages requires you to use goto, and unfortunally for embedded programming you are usually forced to use an inadequate and primitive language.

      Basically, the whole task becomes one big dirty trick.

  57. Re:One word.. J... by maxwell+demon · · Score: 1

    There is an assumption that code is always meant for humans to read.

    Well, some people like trivial literature, others like to read something more demanding. :-)

    --
    The Tao of math: The numbers you can count are not the real numbers.
  58. We in the Linux camp never do that sorta stuff... by Becausegodhasmademe · · Score: 2, Funny

    That's the good thing about open source! All of the dirty hacks the devs use eventually get weeded out of the code as time goes on! Honest!

  59. I program small games by selven · · Score: 3, Funny

    I always just hard-code all my levels - it's easier to just go back and recompile (which takes 15 seconds in C or 0 seconds in python) than code all the extra logic in for reading from files. As another plus, this makes it harder for other people to cheat. Speaking of cheating, once I called my player save file "makefile" to discourage people from looking at it or modifying it.

    And, I never split my code into multiple files - scroll and Ctrl+F were good enough for my grandfather, and they're good enough for me!

    1. Re:I program small games by dkf · · Score: 1

      Speaking of cheating, once I called my player save file "makefile" to discourage people from looking at it or modifying it.

      I think you'll find that 'sendmail.cf' works even better there.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
  60. Re:Here's another one... by Tuna_Shooter · · Score: 5, Interesting

    This is the code for the Apollo 11 lunar lander flight computer.

    http://code.google.com/p/virtualagc/source/browse/trunk/Luminary099/LUNAR_LANDING_GUIDANCE_EQUATIONS.s?r=258

    and yes some of my code is in there along with the equivalent of a few "goto's

    Lots of bright people worked on this and in some circumstances a "goto" is required.

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  61. Getting around encapsulation by s31523 · · Score: 1

    I use a lot of Ada in my job. There was one control feature that had to be hacked in such that event X in process X needed to terminate a condition in another process. Rather than putting in the traditional communication events through the RTOS with appropriate procedure/function handlers, this is what was done (it needed to be done *NOW*, apparently):


    procedure foo is
    type state_type is ( message_on, message_off );
    -- This is the same state the message can be in package Y
    state : state_type;
    pragma import (Ada, state , "packagey_message_x_state");

    begin
    state := message_off;
    end foo;

    The pragma import is like doing an extern in C. Basically this procedure just aliased ton the internal state variable and cleared it. Nasty, nasty code.

    1. Re:Getting around encapsulation by Anonymous Coward · · Score: 1, Informative

      Actually, no it didn't. You just got lucky. The Ada standard says the compiler is allowed to assume a variable is not aliased unless it is marked aliased or volatile (or atomic, which also makes it volatile). One of my compiler would have worked fine, the other would optimize this away.

  62. Had something similar happen by Veretax · · Score: 1

    We had a project in a class on the Motorola 68K Processor using assembly to build a circuit to represent a particular lighting intersection. We then had to write the code for the timings or for the switches for when new cars arrived. Everything was going well, we had a very elegant piece of code and we tested it in a simulator and it seemed to work fine, but the last week or so when it came time to build everything and demonstrated it, the thing was just not working.

    We ended up tearing it down to the drivers for the lights and testing each one individual to verify they were good, and after three weeks of work I narrowed it down to a section of counter code that was not incrementing. I looked at that code for hours, and the lab tech didn't know why it wasn't working either. Then on a whim I grabbed somebody's board with the 68K on it and switched it with ours, and the thing worked. Turned out several of the boards had been fried by some group earlier in the week we were beginning to test it.
    Man was I mad, We didn't have the code from before we scrapped it down to simple timers, and even if we did, there wasn't time to build the circuit, so we built it as quickly as we could doing the bare bones and passed. Man were we pissed though.

  63. Huh? by FlyByPC · · Score: 1

    Have you ever needed to insert terrible code to make something work at the last minute?

    Do you mean, have I ever *not* done this? Hmm... hard to say. Probably not.

    --
    Paleotechnologist and connoisseur of pretty shiny things.
  64. The Fucksort Incident by ari_j · · Score: 5, Funny

    Back in college, we were at a programming competition and I was the on-the-keyboard coder for one of the problems. We had 10 minutes for the problem and I coded it quickly, having decided on the best algorithm before sitting down. Part of the solution was a sorting routine on a list. We were using Visual C++ although we were all not C++ experts at the time, and so rather than mess with the STL and the possibility of having to read documentation, I did it all from scratch. I knew that sort was already in use by the standard library, so I called my routine mysort.

    Apparently, however, Visual C++ includes a mysort in its standard library. So, with the clock ticking down and the solution's only impediment to our victory being an identifier conflict, I renamed the routine the way that any one of us would have: myfuckingsort. We won the competition.

    In this particular competition, the judges were not supposed to read our code - they just run the output of your code on the input and check for correct output - so I felt safe when I typed what I did. However, one of them came up to us afterwards and told us that they do in fact usually read the code of the winning team to see if we did anything unique in our solution. Yep. Sure did. And my classmates and professors never did let me live down what was affectionately nicknamed the fucksort algorithm.

    1. Re:The Fucksort Incident by Dr.+Manhattan · · Score: 1
      I once had a problem where a license manager would fail without giving a reason. During development I had, in my code, a printf which said, "No licence, no frickin' error" - which I forgot to remove before shipping. It was about a year before we'd patched all the customers. At least it wasn't a stronger expletive - but I always keep my editorial comments in the comments now.

      I heard of some coder being told to implement some braindead feature... and he called the conditional variable controlling the behavior, "CustomerIsAnIdiot". But they didn't strip debugging symbols, and while the customer may have been an idiot, they knew how to use the "strings" command...

      --
      PHEM - party like it's 1997-2003!
    2. Re:The Fucksort Incident by Comatose51 · · Score: 1

      fucksort - a sorting algorithm will go for as long as it takes to get the job done, all night if needed

      --
      EvilCON - Made Famous by /.
  65. I see two unconditional jumps here by krischik · · Score: 2, Insightful

    But I might have missed some. There is not much difference between "return 0;" and "ret=0; goto exit_function;". Both are unconditional jumps there is no rational reason why one should be "considered harmful" and the other not.

    1. Re:I see two unconditional jumps here by bcboy · · Score: 1

      But I might have missed some. There is not much difference between "return 0;" and "ret=0; goto exit_function;". Both are unconditional jumps there is no rational reason why one should be "considered harmful" and the other not.

      If there are resource allocations, or at any time in the future resource allocations may be added, there is a huge difference between these two in terms of maintainability. A single point of return makes it trivial to ensure that all allocations are properly freed.

      There are two types of functions containing multiple points of return: those with bugs, and those that will have bugs. In a large project, with many engineers, you can reliably find bugs simply by searching for functions with multiple return statements. They're practically always buggy.

    2. Re:I see two unconditional jumps here by SL+Baur · · Score: 1

      There is not much difference between "return 0;" and "ret=0; goto exit_function;".

      Indeed.

      Both are unconditional jumps there is no rational reason why one should be "considered harmful" and the other not.

      The most anal of the anal retentives of the goto-less persuasion do indeed consider them the same and consider both harmful. Wirth's original Pascal did not have a return for that reason. I'm not sure why he allowed a goto and no return. He later reversed himself in Modula II where he added return, but removed goto.

      Languages that provide a rich set of control structures (an if statement has an implied goto too) do not need goto. Icon (my favorite language for recreational coding) http://www.cs.arizona.edu/icon/refernce/ref.htm does not need a goto. Neither does the Unix shell.

      Low level languages intended for systems programming do need a goto for the reason I noted above - every prefetched byte in the icache counts and you DO NOT want to mix slow path error handling code in with hot path usual case code. Even Ada, which otherwise frowns at non-local flow of control, provides a goto.

    3. Re:I see two unconditional jumps here by krischik · · Score: 1

      Well we are in general agreement here :-)

  66. select "nothing to see here move along..." from du by Anonymous Coward · · Score: 0

    select "nothing to see here move along..." from dual;

  67. Management and deadlines by StoatBringer · · Score: 1

    A lot of terrible code is a result of management forcing unrealistic deadlines on developers, or refusing to slip a deadline to accommodate some unforeseen problem.

    I worked on a large data visualisation application with an unrealistic deadline, which our department was writing for another department, on their budget. In order to prevent it from eating into our budget money, it had to be released by a certain date. It needed several months more than that to be even nearly ready, but when the deadline came the managers announced that it was finished and released on time. Management high-fives all round. Then it immediately announced that the customers couldn't use it yet because there were some minor bugs which had suddenly been discovered (i.e. all the missing features which would make it any use at all).

    I also had a boss who would give you something to do, make changes to the design on a daily basis while you were doing it, then before it was anywhere near ready demand that you stop work on it immediately, check the (unfinished, untested, part built) code in and start work on something completely different. He did this to all the developers, and the code was riddled with overlapping #ifdefs around chunks of unfinished code just so the build didn't break. Then of course he announced "Good news, everybody! We're going live in three weeks!" when the cobbled-together mess was at least six months from being usable. Cue more panic-coding just to make things work, and then the deadline came and went because he'd thought up yet more wacky features to add, starting the cycle all over again. Bug database? Change requests? Unit tests? Peer reviews? Documentation? No such luck. Even the features he wanted weren't clearly defined, you just got a two-hour rambling phone call which contained about five minute's worth of useful information (but it didn't matter, because he'd change his mind when you half-done developing it, or forget how he wanted it doing and yell because you doing it how he originally asked).

    It's like those sci-fi films where the ship breaks down.
    Captain: How long will it take to fix the engines?
    Engineer: At least 24 hours, sir.
    Captain: You've got 8, now get to it.
    Engineer: No sir, really. 24 hours minimum if nothing else goes wrong.
    Captain: We take off in 8! You have your orders.
    Engineer: But seriously, we can't...
    Captain: La-la-la-la I can't hear you!

    --
    Cress, cress, lovely lovely cress
  68. On Error Goto ErrorTrap by johnshirley · · Score: 1

    I use GOTO regularly while debugging and even in some production-level stuff. I've cultured the good|bad habit of leaving 'on error goto errortrap' in code. Predictable errors are one thing. It's those unpredictable ones I usually need to have the whole thing stop without causing problems. Do not pass go, do not collect $200, and absolutely never, ever 'on error resume next'.

    There was some code that another sysadmin wrote long ago at work that was doing something like sifting through a huge file tree, checking the files' attributes and content, then deleting the file if certain criteria had been met. Something happened with one of the checks where instead of bailing out, it just started deleting files... all 2.5 million of them.

    Thankfully, we have hourly backups.

    Reviewing the problem, the first line of their code was 'on error resume next'. They didn't know why it was there, but that's "just the way we've always done it"... which is obviously a warning flag. I changed it to a GOTO -- explained the whole error trap thing to them in painful detail -- then ran it again. The GOTO and error trap did exactly what was expected so we could fix the problem with the object tests... without risk of destroying live data.

    Sure, there are better things than the GOTO out there, but to borrow the analogy from hairyfeet, once in a while, you still need a chainsaw to cut down a tree.

  69. A good example by azgard · · Score: 1

    I had a good example of goto in my code recently. It was searching through linear hash table. So you start in the middle of the table, and when you are at the end, you want to restart from the beginning.

    So I set up a guard pointer (first at the end of table), then go through the table looking for my element (until I get to the guard pointer), at the end, if the current pointer equals guard pointer (I haven't found the element), I goto to the loop again, but this time the guard is set to the original starting point.

    I challenge you to rewrite this without goto and without duplication of the search loop.

    1. Re:A good example by clone53421 · · Score: 1

      Either roll the current pointer back while still inside the loop or make it into a function and call it twice.

      --
      Alexander Peter Kristopeit bought his basement from his mommy for one dollar.
    2. Re:A good example by Anonymous Coward · · Score: 0

      using std;
      vector Table;
      FillTable(Table); // fill it up with stuff
      vector::iterator Start = Table.begin();
      vector::iterator End = Table.end();
      vector::iterator Middle = Table.begin() + SomeAmount;
      vector::iterator Found = End;

      if ( (Found = find(Start, Middle, 100)) != End ||
                (Found = find(Middle, End, 100)) != End)
      { //found
      } // posted anon to keep my insightful mods,

      I mean I've got my search the wrong way round & my logic is probably wrong. But you're all idiots and you need to leave C behind.

  70. 'One return' by Merdalors · · Score: 1

    The most common use of "goto" in that circumstance is to enforce "only one return".

    Which is every bit the pedantic lunacy that goto-hate is.

    Not necessarily: sometimes you need to free memory, resources, etc.

    I don't use goto anymore, but back in the days of 16-bit and 12K stack, where we had to malloc() local variables, a 'one return' goto proved useful to branch to free() without excessively nested 'if's.

    --
    Slashdot entertains. Windows pays the mortgage.
  71. Obligatory... by Anonymous Coward · · Score: 0

    http://xkcd.com/292/

  72. The dreaded deadline hack by cslewis2007 · · Score: 1

    I think a better question to have asked would be, have you ever NOT had to insert something into code as a deadline approached, that you knew in your heart of hearts was nothing less than the worst possible hack imaginable.

  73. many moons ago... by Anonymous Coward · · Score: 0

    This is going back a bit, to around the late 80's in fact.
    We were sat at a copy party trying to finish writing a intro we'd planned to release at the party (a scroller in blitted on fonts using halfbrite shading over a funky moving picture, at the time quite nifty) but we'd saved the bitmap with all the fonts as a 1 layer amiga bitmap, and due to memory restrictions enforced by dpaint they had to be no wider than 400 pixels I think. So I had wrote some routine to process the ascii text we wanted to display, and every nth position from the base position of A, it incremented a Y counter for the blitter source map so say H would be on row two and 30pixels down the bitmap and say +80 in the X so the bit blitter could pick up just that letter image for its source. Only something was very wrong with my logic somewhere and for ages it refused to print certain letters out, instead going slightly mad and printing random garbage instead, and I hadn't had any sleep for two days and was the only coder in our group present . So we wrote the entire scrolltext in what passed for leetspeak in the day, managing to avoid the problem letters completely although it looked a bit insane on the day.
    After a good nights sleep, it was a one line fix to sort out (and involved a pointer looping under certain conditions), but of course we'd already released the demo and everyone had gone home...

  74. Re:Here's another one... by Anonymous Coward · · Score: 0

    This is the code for the Apollo 11 lunar lander flight computer.

    http://code.google.com/p/virtualagc/source/browse/trunk/Luminary099/LUNAR_LANDING_GUIDANCE_EQUATIONS.s?r=258

    and yes some of my code is in there along with the equivalent of a few "goto's

    Lots of bright people worked on this and in some circumstances a "goto" is required.

    Help me out here, then. You're one of programming's elders, landed guys on the moon, best war stories ever. The epitome of professional code design, the ne plus ultra of deployed applications.

    One question, then: why "Tuna Shooter"? Was there ballistic toro involved in Apollo?

  75. the worst I have done and seen by Anonymous Coward · · Score: 0

    if((login.equals("geust")&&password("1234")) || loginOk(login, password))
    .
    while(fuckupCount 100) {... if(!startApp(app)) fuckupCount++;}
    .
    . //someone used the wrong value for pi and all the functions fave been fudged to work...
    double pi_ish = 3.1415673;
    .
    catch(NumericFormatException e) { //there was a bug we cant fix... stop reporting the errorr
    }
    catch(Exception e) {
    logError(e);
    }

  76. setjmp, longjmp by Anonymous Coward · · Score: 1, Informative

    Actually, C has functions that are supposed to do this and work; setjmp and longjmp are supposed to let you jump between functions etc and unwind the stack; if I recall correctly, I even used them for interrupt handling code in MS DOS.

  77. Re:Here's another one... by Anonymous Coward · · Score: 0

    This is machine code. Gotos and conditional gotos are the only control statements you have!

  78. Goto Elimination by omb · · Score: 1

    Goto s can always be eliminated, with a state variable and a __repeated__ test. But at a cost, not a large cost, but extra code and execution both. In fact, the old academic fad against goto was a consequence of the dreadful programs that used to be written in FORTRAN and Cobol, in my view "perform" is far worse.

    So more modern languages have specialised goto s, switch, break, try, catch, finally; which are clearer, even though C, C++ confused endcase and break loop from BCPL. Yet some GOTO s remain the clearest way of writing code, I do not like the state-retest one bit more and as for the suggestions that you break an integral piece of logic into 3+ subroutines, I find that crazy. I like the logic, and thus the code to read down the page, to the greatest extent practical, even if you have a 1000 line routine.

    I do not like the style of C++ and Java coding where any given bit of logic is spread across 4 files and mandates the use of a code visualizer eg SourceNavigator, or an IDE.

    Code should be as simple and as easy to read and understand as possible. Thus puttting things in subroutines should reflect that they are used more than once, and are an execution abstraction.

    This is why "ho-hum" rules, and most coding standards and metrics stuff leads to bad code, eg I dont want large block comments, which I can assume were never debugged and are out of date to interrupt the code. If the algorithm is unusual or complex a link, see ... surfices.

  79. Re:Here's another one... by Tuna_Shooter · · Score: 1

    Exactly.....

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  80. Recursive List Comprehension by rainmaestro · · Score: 1

    First, a brief trick from my school days. We had a professor who didn't even look at the source. He'd come by, you'd "run" the app, and he'd look at the output. I'd forgotten about an assignment, so right before class I ran the calculation we were supposed to be "solving" on my calculator, hard-coded a cout in the app to print the answer, and stuck a pause in there to make it look like it is working. One of only three people who passed the assignment.

    ------------

    Now the real one:

    This one happened the night before I was supposed to deliver a milestone build. Short development time, lots of work, we've all had 'em.

    So I'm working on a function that is taking all of the inputs and generating a list of all combinations. I haven't slept in about 2 days, I'm wired on caffeine. The code I end up with (quickest to write) looks like this:

    *Note, these are just placeholder variable names, the real source code used descriptive names, used the values to pull data out of classes, etc*

    x = [1,2,3,4,5]
    y1 = [8,9,0]
    y2 = ['a', 'b', 'c']
    y3 = ['w', 'x', 'y', 'z']
    x = [[e, f, g, h] for e in x for f in y1 for g in y2 for h in y3]

    Keep in mind that in the actual function, it would have gone up to y11, with all 11 being parsed in that one list comprehension.

    It works great, very fast, but it is *completely* unreadable. The code is still there (with about a page worth of comments). That one line convinced me to never consume seven 2-liters of Mountain Dew in a day and try to program. I don't drink soda/tea/coffee very often. Hell, I probably could have written something better DRUNK.

  81. Re:Here's another one... by Tuna_Shooter · · Score: 1

    Yes there was. Lots of issues involved if the systems went down. I used to have the protocols in the attic someplace. I'll look up there but i haven't looked at them since i got my divorce I might just weep nostalgic.
    Sorry

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  82. Re:Here's another one... by sburchill · · Score: 2, Interesting

    I really love this bit :

    DMP*    VXSC
            GAINBRAK,1    # NUMERO MYSTERIOSO
            ANGTERM

    --
    sbb
  83. Coroutines by Unoti · · Score: 1

    What exactly is that a good solution to?

    It's one partial component you might use to implement Coroutines. or you might use it as a building block for implementing green threads or some other kind of cooperative multitasking. You'd want to wrap it in macros, or better yet, use setjmp or a real programming language like Scala or Erlang... Come to think of it, you asked what this is a good solution for, not a crappy solution... hmm...

    1. Re:Coroutines by QuoteMstr · · Score: 1

      Safe, standard "coroutines" in C. The code given in the article can be further optimized by using gcc's computed goto, but the effect is the same.

  84. Re:Here's another one... by Tuna_Shooter · · Score: 2, Interesting

    # Page 731
    # BURN, BABY, BURN -- MASTER IGNITION ROUTINE

                    BANK 36
                    SETLOC P40S
                    BANK
                    EBANK= WHICH
                    COUNT* $$/P40

    --
    *--- Sometimes a majority only means that all the fools are on the same side. ---*
  85. No by Anonymous Coward · · Score: 0

    No. I am never 'at the last minute' and I am more competent than that. You losers just put your feet in it. I hope you all get the sack as you deserve.

  86. Not the only lesson by Jonathan · · Score: 4, Insightful

    Well, in part, but another important lesson in science labs is learning to report the truth, even if is disappointing and not what you want. This is an important lesson and unfortunately even some well known scientists don't learn it,

    1. Re:Not the only lesson by ceoyoyo · · Score: 1

      Mod parent up. The GP's teacher didn't understand what education was meant to be about. He promoted learning the fact and completely missed that the goal is actually to learn how to FIND the fact when you need to know something that's not conveniently written at the back of the book.

      Education is not about memorizing facts.

    2. Re:Not the only lesson by DrWho520 · · Score: 1

      I did not catch on until well after being rid of Chem Lab, but reverse engineering results was the expected practice. Physics Lab was about carefully assembling, conducting and measuring experiments, then performing error analysis to explain differences between experimental results and theory. According to my chemistry major friends, working backwards from the answer was accepted because the lab TAs had no expectations of students performing the experiments well. As a Physics major, I spent a great deal of time in the lab trying to perform the experiment correctly, but could never get the exact answer. Others would phone in the experiment and spend 30 minutes reverse engineering the expected numbers. Since my numbers were always a bit off, I generally earned 75-85% on my labs.

      I guess I should have caught on earlier.

      --
      The cancel button is your friend. Do not hesitate to use it.
    3. Re:Not the only lesson by HornWumpus · · Score: 1

      Do both.

      Know what your experimental results should be by reverse engineering the final answer back to the experiment.

      Now you know if your experiment is within range of the correct answer as soon as the process is over. You've already done the analysis backwards.

      That way you get at another chance at running the experiment before resorting to pure fudge.

      Dad taught P-chem. He laughed about some of the wrong fudged answers he got. There is nothing more obvious then making a mistake when fudging results.

      --
      John McAfee 'It was like that time I hired that Bangkok prostitute; to do my taxes, while I fucked my accountant'
  87. COBOL compilers can bug out... by phorm · · Score: 1

    I once had a program that kept coming up with a really odd numerical error. I ended up tracing it back by printing out various variables along the way so I could make sure that the interim calculations were correct.

    However, when I printed out one particular variable, the code suddenly gave the correct result. Removed the other debug prints, and it still worked. However, if I once again removed the line that echoed out the variable-in-question, it would screw up.

    I checked all around that statement to make sure there were no termination issues (aka it wasn't the "WRITE VAR1" statement at fault, but a higher-up that wasn't terminated until my debug WRITE) and there was nada. Even my prof had a look and found nothing, but the output was definitely bugged without that line.

    We lost a few marks for having a debug line in our final output, but nobody ever was able to figure out why it wouldn't calculate properly without it.

    1. Re:COBOL compilers can bug out... by SpinyNorman · · Score: 1

      Could have been a compiler (code generation) bug - you could have checked the assembler generated - or could have been a bug somewhere else in your program causing corruption. Insert/delete an arbitrary bit of code (debug statement) and the thing being corrupted changes and the bug may **appear** to have gone away (it hasn't, but it's just corrupting something harmles instead e.g. unused memory).

  88. note really code by sanguisdex · · Score: 2, Interesting

    Not that I have done this but I have seen plenty of web desigers use a css 'display:none' or before that was happening put comments tags around data that they did not want the site visitor to see.

  89. U2 is my favorite rock group by Anonymous Coward · · Score: 0

    In some CAD software getting ready for a show, a programmer entered this late night gem causing significant head banging (into the concrete wall). Something like:

    if (object == U2) continue; // U2 disallowed cuz it is my favorite rock group

    Of course all of the components on a schematic are traditionally named U1, U2, U3...

    This might be the same guy that complained I was playing music on the weekend because he was trying to sleep in his cube, doh!

  90. Ahem by Quick+Reply · · Score: 1

    // Workaround for strange CG antialiasing of the Ahem font. Limit to the Web font version.
            if (isCustomFont()) {
    #ifdef BUILDING_ON_TIGER
                    RetainPtr fullName(AdoptCF, wkCopyFullFontName(m_font.cgFont()));
    #else
                    RetainPtr fullName(AdoptCF, CGFontCopyFullName(m_font.cgFont()));
    #endif
                    String nameStr(fullName.get());
                    m_allowFontSmoothing = (nameStr != "Ahem");
            }

  91. Hex Editor Fun by Anonymous Coward · · Score: 1, Interesting

    Working on an application for a now defunct airline. Developers embedded similar to the following Oracle 7.3 SQL in an executable:

    select *
    from bob A, fred B
    where A.key = B.key;

    Rule-based optimizer depended on ordering the tables in the from clause correctly for an efficient join (driving table will be last in the list), but the developers got the order wrong. So, I used a hex editor to reverse the aliases A and B in the from clause in the executable. Voila, performance went from dog slow to blisteringly quick without a recompile (no time for that).

  92. It's SOP ... by Anonymous Coward · · Score: 0

    for politicians .

  93. Re:Here's another one... by Chapter80 · · Score: 3, Funny

    This is the code for the Apollo 11 lunar lander flight computer.

    HELP!

    I'm trying to get this code to work. I'm at an altitude of 6,000 ft, hovering over the Sea of Tranquility, and the darn thing keeps crashing! (The code, not the lunar module.)

    PLEASE don't connect me to that Bangalor helpdesk again! I am in serious trouble here!

    Has this been tested for Y2K compliance?
    Did we not pay our last support bill?

    - Major Tom

  94. Just wondering by DrWho520 · · Score: 1

    Have you found it yet?

    --
    The cancel button is your friend. Do not hesitate to use it.
  95. Word Conversion by Anonymous Coward · · Score: 2, Interesting

    I remember 15 years or so back; I was trying to get an application convert a text file into a Word document. I was using all these nice OLE calls from within Delphi but for some reason it didn't work.

    The deadline was looming, so I ended writing a function that copied the files and renamed the extension to DOC. When opening it in Word it didn't show any errors. Unfortunately my client found out and went ballistic. By that time I luckily had the word conversion code working and was able to provide a new executable that worked as requested.

  96. Re:Here's another one... by gknoy · · Score: 1

    "Ballistic toro"? Flying cows? flying bull[shit]? I confess I don't quite understand the phrase.

  97. Fucking idiots by QuoteMstr · · Score: 1

    If you're working in an environment in which variable names and comments matter, then you still write with descriptive variable names and comments, and just pre-process the source to remove comments and shorten variable names. Writing obfuscated code directly is just foolish.

    1. Re:Fucking idiots by WinPimp2K · · Score: 1

      I was replying to the poster who referenced caluclated GOTOs as WMDs

      "If you're working in an environment in which variable names and comments matter, then you still write with descriptive variable names and comments, and just pre-process the source"

      Not necessarily - you made an assumption regarding what tools might be available. What is this "pre-processing" you speak of?

      Before you get your panties in too big a bunch, this was a Point-of-sale app written in the early 80's for the TRS-80 model IV. The language was whatever BASIC interpeter the machine shipped with.
      The prior programmer (who really really liked TRS-80s - he specced the app to run on the Mod IV in late 1983!) used a book with a rocket and a wizard on the cover as his programming bible. The title was something like "Better and Faster BASIC". It was filled with cute little code snippets to do things like storing a date in a two byte integer - that overflowed after 12/31/95. It was also filled with other memory saving tricks like calculating GOTOs and overlays out the wazoo. So not only did you not know what line the code would GOTO, you might not know what overlay (and therefore what code) would be in RAM when it got there.

       

      --

      You either believe in rational thought or you don't
  98. Re:Here's another one... by show+me+altoids · · Score: 1

    Bah! I want to see the script for the simulation out in the desert/soundstage.

    --
    I feel sorry for people that don't drink, because when they get up in the morning, that's as good as they're gonna feel
  99. I had totally forgotten this... by istartedi · · Score: 1

    ...until somebody mentioned the Wing Commander hack.

    I used to work at an ISP and helped with the custom browser installers burned onto CD-ROMs. During testing we discovered that NT 4 would behave badly if you started using it too soon after the install had completed. No time to figure that one out. It had to ship.

    Solution? Throw up a fake progress dialog that said "configuring settings" that ran for about 30 seconds after everything else was done. We were banking on the user not fiddling with his machine while it was still doing the all-important configuring.

    --
    For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
    1. Re:I had totally forgotten this... by Anonymous Coward · · Score: 0

      Funny that you're using a misquoted phrase in your sig to talk about grammar. The phrase is "for all intents and purposes". And "whom" is still a word, but most people haven't bothered learning how to use it. Simple rule: if you can say "him", then you can say "whom".

  100. Re:Here's another one... by nitehawk214 · · Score: 1

    What does this mean?

    "HERE IS THE PHILOSOPHY OF GUILDENSTERN"

    Was that one of the engineers on the project?

    --
    I'm a good cook. I'm a fantastic eater. - Steven Brust
  101. Re:Here's another one... by nitehawk214 · · Score: 1

    Were you also responsible for some of the code used wtih Apollo 13 as well?

    Cute, but it wasn't a software failure. In fact the computer was able to do things it was not designed for in order to get them home.

    --
    I'm a good cook. I'm a fantastic eater. - Steven Brust
  102. Re:Here's another one... by ironicsky · · Score: 1

    I think this code would be more entertaining if there was a "OMG WTF just happened" with a little ASCII Skull and Cross bones in the comments..

    Just saying :-)

  103. Vapor Code by Anonymous Coward · · Score: 0

    We used to ship "Vapor" Code to make revenue during a quarter. Essentially if a product hadn't completed a test cycle by the due date, we'd ship a placeholder application that would happily install but then when first run would go out and get the latest "updates" which would be the software that was supposed to ship. Not a great practice but it was management's directive. Customers usually waited a few weeks to install the software anyway so the testers and the bug fixers could refine the product using that gap time.

  104. Re: odd messages by An+anonymous+Frank · · Score: 1

    At a place I once worked, the policy was to catch any and all possible outcomes to death, however impossible.

    So I'd taken a habit of coding in a rather verbose and unique message for each condition that should never occur; one day a call came from a client with an odd error message asking users what the score of a game (between a hockey team and a basketball team) was on a specific season final, which helped us quickly identify the relevant portion of code.

    Since the condition was indeed impossible to reach, we were able to return some harsh questions to the dev guy at the client's site, who had meddled with a library without supervision, which turned out to be the root cause of some odd intermittent bugs the client had been suffering of late.

    Sometimes it's fun and helpful to be a little creative, though perhaps it's best to stick to clearer error text, since it initially took the client a whole day to eliminate the theory that a virus was causing the error to appear, instead presuming the application was the culprit.

  105. Great story by Anonymous Coward · · Score: 0

    tell it again! tell it again!

  106. IKVM by GWBasic · · Score: 1

    My current favorite: Use IKVM to convert a java .jar file into a .dll that will work under .Net and Mono!

  107. No code at all by PsiCTO · · Score: 1
    I once dealt with an programmer, Chris, who was motivated only by deadlines in that he believed that success meant the apperance of ticking off a milestone. To wit, 6 or so months after he was let go for total lack of engineering ability (another story itself), I found myself working with the best debugger dude in out group trying to figure out why my code was badly broken. Eventually we thought we should step into a module written by Chris that was supposedly released. Process being what was, Chris had self-tested and self-released it. When the debugger entered, we were greeted with a function body that was empty except for a giant comment saying,

    /* Cam, I don't know what this is supposed to do */ return 0;

    Needless to say, there was a bit of a panic to review all his "released" code ...

  108. CRC collision? by naturaverl · · Score: 1

    FTA one of the hacks was a workaround for a supposed "two-in-a-row" CRC32 collision! What are the odds, I thought? Thats like, getting struck by lightning at the precise moment as scratching the jackpot winning lottery ticket while.... Then it dawned on me... Apparently they only used filenames to generate the first 32-bits of the ID, and they used file contents to generate the second 32-bits. So all one would have to do to cause a collision would be to copy a file to another directory in the project! On the surface it was a good idea, just ruined by bad implementation. Their "quick" solution was to just add a space to the end of one of the files. A more proper solution might have been to change the implementation to use the entire path+filename to generate the first 32-bits. I wonder why they didn't just do that?

    1. Re:CRC collision? by XenonOfArcticus · · Score: 1

      Actually, what you see here as a bug, was actually a feature if you read the article. They used this technique to unify multiple copies of identical content (same filename and contents) appearing at different places in the resource data.

      --
      -- There is no truth. There is only Perception. To Percieve is to Exist.
  109. I laugh at the college assignments listed above by KZigurs · · Score: 1

    In production systems I do like to occasionally fight for a time off ('cleanup timeout or I quit!') and let someone else to have a stab at the code I feel I have fucked, really, really, fucked, up. And funny enough, when they do account for most/all the edge cases, two or three different input paths as per specifications and variations in states, it might not be the same, it might not be worse, but for sure as hell I am just about in a WTF mode reading their code as I can imagine anyone reading and deleting 'surplus' code blocks from mine are.

    In real life code sucks. Just sucks, and it just doesn't involve you (again). Unless you manage to position yourself in nuclear plant or simlar critical systems where your inputs are guaranteed to be x to y and if not - oh well, it's too late anyway.

    And as a word of warning - if you see a code that appears to be equal to 'if (1 == 1) return 1;)' - well, this is the time to become _extremely_ careful.

    (*When I'm not drunk I dream of working in true RT-embeded systems with watchdogs, crystals, documentation describing cycles-per-instruction and no stupid heap sharing...)

  110. In a word: No. by StikyPad · · Score: 1

    Have you ever needed to insert terrible code to make something work at the last minute?

    A properly designed project will never require the last-minute insertion of bad code. Rather, proper planning and foresight allows terrible code to be implemented in each and every step of the process.

    I've found an excellent practice is to define what problem I want to solve, and who my target audience is. In the first case, the problem I'm trying to solve is often the same: I want to make money. And my target audience is anyone who likes purple primates, which is obviously everyone. Next, since I know I can't please all the people all the time, I throw their expectations out the window and instead create whatever I want.

    Also, a little tip for you beginners: Recursion is super fast, so use it for EVERYTHING. In fact, you should only need one function or method in the entire program. If recursion is too intimidating, you can start out by overloading all of your methods to a single identifier. Eventually you can merge them together by adding optional parameters to a base method.. but DON'T be tempted to use case switches. Instead, use nested if statements, like this: if ![condition1] {if ![condition2] {if ![condition3] {[dostuff for condition4]} else {[dostuff for condition3]} else {[dostuff for condition2]} else {[dostuff for condition1]} Also avoid line breaks, the way I did, because they make your program run slower. Obviously 1 line is less than 2 lines, so use this to your advantage.

    1. Re:In a word: No. by /dev/trash · · Score: 1

      You're still in college right?

  111. Re:Here's another one... by More_Cowbell · · Score: 1

    That's just because you don'rt eat enough sushi (unless your are just kidding/trolling).
    Toro = fatty Bluefin tuna belly :: http://en.wikipedia.org/wiki/List_of_sushi_and_sashimi_ingredients#Finfish

    --
    Experience teaches only the teachable. -AH
  112. My personal favorite... by gillbates · · Score: 1

    char * password = "password";
    ...
    scanf("%s",password);

    This little lovely gem is likely to get past most levels of testing, and fail miserably, insecurely, in the field. No, I haven't personally done this, but I've long suspected similar code is the reason for those "You can't have more than 8 characters in your password..." limitations on some websites.

    Someday I'm going to start a website for absolutely subversive C source code. It will be my personal therapy...

    --
    The society for a thought-free internet welcomes you.
    1. Re:My personal favorite... by julesh · · Score: 1

      I've long suspected similar code is the reason for those "You can't have more than 8 characters in your password..." limitations on some websites.

      Chances are this is because they're using the original Unix 'crypt' function to hash passwords, which works by encrypting a base string with a 56-bit DES key derived from the password by taking the least 7 significant bits of each of the first 8 characters, ignoring the rest of them. By limiting the length to 8 chars, you avoid the security problem caused by people who think that 'password498+!%' is a strong password because it's got digits and symbols in it... except it hasn't, because they're ignored.

  113. Doom 2 Sector Hack by adiposity · · Score: 1

    Doom 2 Sector Hack:

    From p_enemy.c:

    ==============

    if (gamemap == 7)
            {
                    if (mo->type == MT_FATSO)
                    {
                    junk.tag = 666;
                    EV_DoFloor(&junk,lowerFloorToLowest);
                    return;
                    }

                    if (mo->type == MT_BABY)
                    {
                    junk.tag = 667;
                    EV_DoFloor(&junk,raiseToTexture);
                    return;
                    }
            }

    ==============

    If anyone remembers the "outpost of hell" level of Doom2, this code caused sector 666 (doors to outer area) to drop after all the Manucubi (fat guys with flamethrowers) were killed, freeing all the Arachnotrons (baby spider demons), and raised sector 667 (stair to end of level) after all Arachnotrons were killed.

    I used to design levels for Doom2 and I came across this interesting behavior when trying to force doors to open after enemy deaths. I finally realized that only on level 7, and only sectors 666/667 were affected in exactly this way. Sure enough, when I was able to view the Doom2 source, there was the "ugly hack."

    -Dan

  114. Just one? by Anonymous Coward · · Score: 0

    I once documented a web server written in COBOL.

    The entire server is an amalgamation of dirty coding tricks.

  115. Re:Here's another one... by Anonymous Coward · · Score: 0

    My favourites were the...

    # TRASHY LITTLE SUBROUTINES
    (I originally planned to quote more of the code, but apparently a snippet of the Apollo 11 lunar lander flight code isn't "geeky" enough for /. (too many 'junk' characters in that). Who knew?

    (about 3/4 down the page)

  116. Re:Here's another one... by Crazy+Eight · · Score: 1

    That could be the character in Hamlet.

  117. Removing Parts by eulernet · · Score: 1

    In 1996, I had to finish a game that was coded by another guy (who had quit).
    There was a weird bug, when you took a sword and jump on the same place, after 2-3 minutes, the player passed through the floor and kept falling (reappearing at the top of the screen).
    My boss wanted to know how much time I would need to fix this bug, but I sincerely told him I didn't know.
    He immediately asked to remove the sword from the game.
    In the same game, there were 2 more unfinished levels, that had probably required 3 months of graphic work (they were graphically finished).
    Since the game had to be released soon, we didn't include these levels (this was 20% of the whole game !).

    In another company, a similar fact appeared: we had to release a game and there were some levels to integrate.
    The levels were simply ignored.

  118. Once, with a build system... by JonLatane · · Score: 1

    At a previous job of mine, I was working with the SCons build system; it's basically Make, but written in Python. It's actually really nice if you know Python, but also fairly slow. In it, every filesystem object (files and directories) are maintained as "Nodes" in a big graph.

    Anyway, the project was using an old version of SCons along with lots of legacy code, and with this version, for some reason, when my build script was added, a conflict resulted where a Node in the build system representing a file was initialized twice, once as a directory, once as a file (it was actually a file).

    Nowhere in my build script was this file even referenced; it wasn't even a dependency of any of the stuff being generated by my code. After hours of trying to find what was causing the conflict, I eventually figured out I could call File("theFile") to (sort of) "cast" the Node as being a File in the build system, and it would work. To this day, I believe that's how it's implemented, and I have no idea why it worked. :)

  119. Short-circuit AND by drfreak · · Score: 1

    Although hard-coding things is generally frowned upon, I can see why it is used for "quick and dirty" reasons. What really caused the FAIL in the OP's code is the short-circuit AND (&&). If a single & was used, the artist would have seen their object.

  120. I wish I knew this "Good developer"! by Canberra+Bob · · Score: 1

    Because "Good developers" will never be thrown into a project that is running over time and budget?
    Because "Good developers" will never have to work with poorly designed legacy systems?
    Because "Good developers" will never have deadlines moved forward for commercial reasons against all technical advice?
    Because "Good developers" don't have to deal with last minute change orders?
    Because "Good developers" review all bugs reported for every supporting application they use and even know of bugs in the supporting applications before they are reported?
    Because "Good developers" only ever work on projects with other "Good developers" and so never discover bugs in libraries / other code they are calling at the last minute?
    Because "Good developers" are never temporarily pulled off projects to work on a system crash type issue and thus have their own projects fall behind?

    I could go on and on and on and on...

    A "Good developer" could test their code until it is bullet proof and will still have problems if one of the supporting libraries also being developed either changes functionality or is buggy. A "Good developer" has no control over situations where the customer says "I want this change in production by tomorrow and accept the risks associated with the lack of testing".

    Many of us dream of this utopian universe where none of those conditions occur and we could all be "Good developers". Until that time I, I am always wary of people claiming to be "Good developers" who never run into these problems as, with very few exceptions, they have never worked on any decently sized commercial app.

  121. Bravo, robfoo by XenonOfArcticus · · Score: 2, Insightful

    Let others smack you down, but with nearly 30 years of programming experience in numerous languages, I'm with you. Indented branching flow seems clean, stable and maintainable. I got dissed for a job i applied for because my code was designed this way instead of the "enlightened" way of throwing exceptions. Exceptions are ok, I guess, if everything is a C++ objects that self-destructs when it goes out of scope, but reality doesn't always work that way. In retrospect, I'm glad I'm not at that job.

    --
    -- There is no truth. There is only Perception. To Percieve is to Exist.
  122. Anonymous Coward by Anonymous Coward · · Score: 0

    GOTO's are like jump instructions in assembler.
    Every program made must have a jump instruction.

    GOTO's jump to places in the code
                                those places have different state sets
                                different local variables
                                and you had better get the there without any non-maskable interrupts diverting you.

    That said - most times a goto is used only to make the code clearer or to escape a failed operation.

    Bill Plaguer said that Clarity of Code is a great asset.
                            So don't use goto's if the surrounding code is likely to change.

  123. Re:Here's another one... by dargaud · · Score: 1

    Whoah... Respect ! Was that a real CPU (what kind ?) or a microcontroller ?
    TRASHY LITTLE SUBROUTINES
    SPECIALIZED "PHASCHNG" SUBROUTINE
    Isn't that spelled Phishing ?

    --
    Non-Linux Penguins ?
  124. Re:Here's another one... by akayani · · Score: 1

    You have an ID 10 T error.

  125. Exactly. by CarpetShark · · Score: 1

    Saved me the trouble of having to say it. Thanks.

  126. Very common, but take precautions by M3wThr33 · · Score: 1

    Towards the end of my projects we had lots of similar hacks. But we have it on a separate BRANCH, IDENTIFY it as a hack so it doesn't get reverse-integrated AND we #define it with the game name around it so it WON'T happen in the other games.

  127. Re:Here's another one... by Anonymous Coward · · Score: 0

    Interesting. Is this some kind of assembly language for an old obscure CPU? I have been coding in assembly language for various architectures but I haven't nothing like that. It's quite different than what I am used to and a lot of keywords/opcodes there seem preety strange.

    Also, why bother excuse yourself for the use of goto equivalent opcodes? People argue that got sucks but only for higher level languages. Goto in assembly is like a JMP or something, of course it's necessary and not to be blamed. I used to be annoyed with how people avoided goto in high level language but even bother about it in assembly?

  128. Re:Here's another one... by Mr2cents · · Score: 1

    Compilers also use gotos.

    --
    "It's too bad that stupidity isn't painful." - Anton LaVey
  129. People don't know how to write tests... by Xenographic · · Score: 1

    > If I'd been the TA, I would have given you 98% too despite your misreading of the spec, even without your "fix". Come on, a 0 for getting it 98% right? With a trivial fix?

    There are a lot of people who care more about the test than the purpose it's supposed to serve. At work, we have a safety guy who gives us safety tests.

    Some of the questions are absurd and do nothing to keep us safer. They could easily be changed to focus on the actual important safety issues we face. But he won't do it. He doesn't want to make the test "easier" even though he's asking people questions that simply aren't relevant to them.

    Our last test was on fire extinguishers. There are four classes of fire: A (solid fueled fires), B (liquid fueled fires), C (electrical fires) and D (metal fires, e.g. from burning magnesium).

    We have absolutely nothing that could case a class D fire at work. We have no fire extinguishers that can extinguish class D fires ANYWHERE. Half of the test was about class D fires.

    We have lots of huge drums of highly flammable liquids (class B fires). There were only two questions about them, and one was "What kind of fire is a class B fire?" There was NO discussion about why you don't pour water on them (because you spread the fire). They did have a question asking what kind of fire water is good for, but it was so indirect it hardly made a point. Because the tests are mainly for the factory workers (but are given to everyone), I don't think that most of them understand why you don't pour water on a gas fire.

    But all of them now know more than they ever cared to about metal fires, because that's the way the test was constructed.