Slashdot Mirror


C Code On GitHub Has the Most "Ugly Hacks"

itwbennett writes: An analysis of GitHub data shows that C developers are creating the most ugly hacks — or are at least the most willing to admit to it. To answer the question of which programming language produces the most ugly hacks, ITworld's Phil Johnson first used the search feature on GitHub, looking for code files that contained the string 'ugly hack'. In that case, C comes up first by a wide margin, with over 181,000 code files containing that string. The rest of the top ten languages were PHP (79k files), JavaScript (38k), C++ (22k), Python (19k), Text (11k), Makefile (11k), HTML, (10k), Java (7k), and Perl (4k). Even when controlling for the number of repositories, C wins the ugly-hack-athon by a landslide, Johnson found.

264 comments

  1. carmack puts it best by Anonymous Coward · · Score: 0

    "oh, this is a hack!"

    1. Re:carmack puts it best by PrescriptionWarning · · Score: 1

      Self preservation and regenerative biological devices known as the human body.

    2. Re:carmack puts it best by DrVxD · · Score: 1

      Degreelessness Mode?

      --
      Not everything that can be measured matters; Not everything that matters can be measured.
  2. Perl by mozumder · · Score: 5, Funny

    Pretty sure people already assume that every line of Perl code is an ugly hack anyways, so they didn't have to write a comment on it.

    1. Re:Perl by dgatwood · · Score: 4, Funny

      To recognize that a line of code is an ugly hack, someone would have to first understand it, and as we all know, only Perl can parse Perl.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    2. Re:Perl by Anonymous Coward · · Score: 0

      Truer words have never been written.

    3. Re:Perl by Anonymous Coward · · Score: 0

      You made that comment so I didn't have to.

    4. Re:Perl by Anonymous Coward · · Score: 0

      As a Perl coder, I came here for this comment, was not disappointed.

      Thank you.

    5. Re:Perl by Anonymous Coward · · Score: 0

      Perl - No idea what it's doing

      PHP - I think I know what it's doing, but I don't

    6. Re:Perl by Anonymous Coward · · Score: 0

      // WARNING: Ugly Hack follows.

      vs.

      # watch this - a very Perl thing to do :)

  3. Such is C by Otome · · Score: 0

    C Code EVERYWHERE has the most "ugly hacks"

    1. Re:Such is C by ShanghaiBill · · Score: 5, Insightful

      C Code EVERYWHERE has the most "ugly hacks"

      Ah, but C also has the most beautiful hacks.

    2. Re:Such is C by Anonymous Coward · · Score: 0

      The good, the bad and the ugly C hacks.

    3. Re:Such is C by dgatwood · · Score: 4, Insightful

      C Code EVERYWHERE has the most "ugly hacks"

      C code is ugly hacks. But how else are you going to write an efficient ring buffer?

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    4. Re:Such is C by Anonymous Coward · · Score: 1

      Beauty is in the eye of the beholder.

      Is a shortcut reliant on the finer details of a cpu - say for example the finer points of 2s complement arithmetic for type int - elegant (because it's cool) or an ugly hack (because it will probably break on some future architecture and is hard to read for the newbie)?

    5. Re:Such is C by dgatwood · · Score: 2

      Depends. Is it wrapped with #if __i386__ || __x86_64__ and followed by a #else clause that contains code without the insane optimization? If so, it is elegant. If not, it is ugly.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    6. Re:Such is C by cfalcon · · Score: 2

      I mean, a lot of code is only meant for one platform type. Not writing code compatible with obsolete processors is no great sin.

    7. Re:Such is C by Darinbob · · Score: 1

      True, but I don't think x86_64 is obsolete just yet...

    8. Re:Such is C by lgw · · Score: 2

      Is a shortcut reliant on the finer details of a cpu - say for example the finer points of 2s complement arithmetic for type int - elegant (because it's cool) or an ugly hack (because it will probably break on some future architecture and is hard to read for the newbie)?

      C originally supported many architectures when it came to number representation - 1 vs 2s compliment, 9 vs 8 bit-bytes and so one. But the current architecture is a self-fulfilling prophesy: software expects it as it's been the nom for so long, and hardware is built that way because software expects it. It's not going anywhere until we get some architecture that breaks everything anyway, even at the highest levels of abstraction, like a quantum computer. Standardization benefits everyone.

      And if you're not comfortable with bit twiddling and bytewise struct layout, C probably isn't for you. Plenty of other languages in the world. Certainly if trivial stuff like (unsigned) -1 as a way to get max int bothers you, you'd probably feel more at home with high-level languages.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    9. Re:Such is C by Anonymous Coward · · Score: 0

      I'm posting from a Debian 8 laptop with the following CPU specs:

      pparadis@devbox1:~$ egrep '^(processor|vendor_id|cpu family|model|address sizes)' /proc/cpuinfo
      processor : 0
      vendor_id : GenuineIntel
      cpu family : 6
      model : 14
      model name : Genuine Intel(R) CPU T2400 @ 1.83GHz
      address sizes : 32 bits physical, 32 bits virtual
      processor : 1
      vendor_id : GenuineIntel
      cpu family : 6
      model : 14
      model name : Genuine Intel(R) CPU T2400 @ 1.83GHz
      address sizes : 32 bits physical, 32 bits virtual

      It's nice to have a distro full of code that works perfectly fine on "obsolete" processors.

    10. Re:Such is C by Darinbob · · Score: 5, Informative

      I think the key difference here is that when someone uses C they want efficient code to some extent. Small, or fast, or both. In other languages the culture is often "do it in the method approved by the sacred elders", and so ugly hacks may be forbidden and the slow/bulky method is preferred, according to the mantra "do not reinvent the wheel because thou are not as wise as the wheel builder". Or the presence of an ugly hack implies that the novice must clearly have been prematurely optimizing, for as the wise men say tomorrow is too soon to optimize.

      For example in Python the claim is that there's almost always only one way to do something, which either means ugly hacks are not possible, or else there's a lack of imagination amongst the programmers.

      The higher level a language is, the more it seems that the goal is to get stuff done fast rather than efficient or elegant.

      Finally, I have actually seen cases where code is labeled an "ugly hack" when it really wasn't a hack at all but rather not as tiny or or elegant as the author wanted.

    11. Re:Such is C by dgatwood · · Score: 1

      I mean, a lot of code is only meant for one platform type. Not writing code compatible with obsolete processors is no great sin.

      Fair enough. Ideally, you should include a generic version without any hackish optimizations, but it isn't strictly required if you don't think you'll ever change CPUs in the future. Either way, if you're writing code that you know is likely to break on a different architecture because of its unique characteristics, IMO, you should at least make it fail to build on any other architecture than the ones you've tested....

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    12. Re: Such is C by Anonymous Coward · · Score: 0

      I have production servers running on some of the first UltraSparc processors. They are 20 years old now.

    13. Re:Such is C by Anne+Thwacks · · Score: 4, Interesting
      Some people may not even remember 10, 12, 18, 24, 36 and 60 bit processors.

      For ugly hacks, you can't beat trying to optimise string ops 8 bit bytes on a 60 bit (Cray) processor - they natively used 6-bit chars, and packed four 15 bit instructions in a word, but required jumps to be aligned on a double word boundary to avoid pipeline stalls. Apart from assembler, I think C is probably the only language that could do it at all.

      (I it tried in Fortran and then realised there were better things to do in life).

      --
      Sent from my ASR33 using ASCII
    14. Re:Such is C by jandersen · · Score: 2

      Ah, but C also has the most beautiful hacks.

      Absolutely; which reminds me of a piece of C code I saw years back, and which I haven't been able to find again - perhaps somebody here would happen to know it. If I remember, it was an algorithm to find the best approximation to a straight line in a bitmap, given the two end points. What I remember is that it featured a rather eye-watering construction of two overlapping switch statements (?) which was syntactically legal, but perhaps shouldn't have been. Anyway, if it rings a bell, please let me know :-)

    15. Re: Such is C by Anonymous Coward · · Score: 0

      Is that really something to brag about?

    16. Re:Such is C by Cow+Jones · · Score: 1

      What I remember is that it featured a rather eye-watering construction of two overlapping switch statements (?) which was syntactically legal, but perhaps shouldn't have been.

      Reminds me of this monstrosity. It's not two overlapping switch statements, but a switch entangled with a do ... while loop. If that sounds familiar, you may be able to find your code from the links in the External References section.

      CJ

      --

      Ah, arrogance and stupidity, all in the same package. How efficient of you. -- Londo Mollari
    17. Re: Such is C by luis_a_espinal · · Score: 5, Insightful

      Is that really something to brag about?

      Yes. If you don't understand why, you have no place in engineering.

    18. Re:Such is C by michelcolman · · Score: 1, Insightful

      Ideally, you should include a generic version without any hackish optimizations, but it isn't strictly required if you don't think you'll ever change CPUs in the future.

      And then your company upgrades its CPUs while you're long gone, and now they need to figure out who the hell wrote that crappy piece of code that keeps crashing on the new CPU, and some other programmer has to rewrite everything from scratch because they can't figure out how your code works and why it's not doing what it's supposed to be doing.

      By the way, that other programmer may just be an older version of you who has completely forgotten what the younger version did there... (not that I have any experience with that, cough)

    19. Re:Such is C by wonkey_monkey · · Score: 2

      it's been the nom for so long

      And it's everywhere, which makes it the om nom.

      --
      systemd is Roko's Basilisk.
    20. Re:Such is C by gl4ss · · Score: 2

      well, it turns out that they evaluated the ioccc repository.

      --
      world was created 5 seconds before this post as it is.
    21. Re:Such is C by michelcolman · · Score: 2

      I remember something similar, called Duff's device. Not two overlapping switch statements (I don't think that's possible), but an intertwined loop and switch. I don't see any references to lines in bitmaps, but it's entirely possibe that the same kind of construction was used for that purpose too.

      send(to, from, count)
      register short *to, *from;
      register count;
      {
              register n = (count + 7) / 8;
              switch (count % 8) {
              case 0: do { *to = *from++;
              case 7: *to = *from++;
              case 6: *to = *from++;
              case 5: *to = *from++;
              case 4: *to = *from++;
              case 3: *to = *from++;
              case 2: *to = *from++;
              case 1: *to = *from++;
                              } while (--n > 0);
              }
      }

    22. Re: Such is C by Anonymous Coward · · Score: 0

      <dalek>
      Explain! Explain!
      </dalek>

    23. Re:Such is C by thogard · · Score: 2

      I've wondered if a software VM that runs (slowly) with a unusual architecture wouldn't be helpful for finding lots of C bugs. Old C wouldn't care if it was 60 bit with 9 bit char and middle-endian.

    24. Re:Such is C by Anonymous Coward · · Score: 0

      What I remember is that it featured a rather eye-watering construction of two overlapping switch statements (?) which was syntactically legal, but perhaps shouldn't have been

      If you grok assembly, Duff's device is perfectly straightforward. A jump is a jump. There's no difference between 'while' jumps and 'switch' jumps.

    25. Re:Such is C by thogard · · Score: 2

      Tom Duff was working on very high speed rendering code for Lucasfilm when he found that.

    26. Re:Such is C by Anonymous Coward · · Score: 0

      2's complement hacks don't have to be wrapped with #if anything. You can do the PDP-11 port later.

    27. Re:Such is C by Anonymous Coward · · Score: 0

      there's almost always only one way to do something

      Who claims that? Try Stackoverflow on ANY Python question and get thirteen different answers.

    28. Re:Such is C by Lord+Crc · · Score: 1

      What I remember is that it featured a rather eye-watering construction of two overlapping switch statements (?) which was syntactically legal, but perhaps shouldn't have been

      Are you think of Duff's Device? It overlaps a switch with a do-while loop: http://en.wikipedia.org/wiki/Duff's_device

    29. Re: Such is C by Andy+Smith · · Score: 1

      I always wonder when I see code like that, which is focused on optimisation, why they use divide and modulo? Aren't they slow? Why wouldn't the coder have used >> 3 instead of the divide by 8, and & 7 instead of the modulo 8? Genuinely asking because these strike me as obvious further speed boosts. Does the compiler automatically make the changes?

    30. Re: Such is C by michelcolman · · Score: 1

      Any decent compiler makes those changes automatically. Probably even with optimisations switched off, since these are such a no-brainer.

    31. Re: Such is C by Anonymous Coward · · Score: 0

      Yes, these kinds of changes (division / multiplication by powers of 8) are trivial for a compiler to perform, and all modern compilers do so.

    32. Re: Such is C by Anonymous Coward · · Score: 0

      Usually the compiler can figure out bit-shifty divs and mults.
      The whole thing about duffs device is not optimization for a cpu, but about a co-routine (eg, you have a perfectly good lzh handler. and you have a good serial handler. how do you integrate the 2 with the minimum of fuss...)

    33. Re: Such is C by Anonymous Coward · · Score: 0

      Does the compiler automatically make the changes?

      Yes. Also, multiplications with any constant is typically split so that it becomes a combination of shifts and adds. The division, modulo and multiplication is kept in the source code to serve as documentation.

    34. Re: Such is C by Anonymous Coward · · Score: 0

      for starters, any modern compiler worth even a little will automatically convert those to exactly what you suggested so why bother muddling with readability?

    35. Re:Such is C by jittles · · Score: 2

      Depends. Is it wrapped with #if __i386__ || __x86_64__ and followed by a #else clause that contains code without the insane optimization? If so, it is elegant. If not, it is ugly.

      I would say it would depend even more on whether or not the programmer profiled the code in question prior to making that optimization change. If there is no perceived or noticeable benefit to this optimization, then there is no reason to put something unreadable and platform specific into your code base. I know I worked on a project once where the dev manager wanted to rewrite an entire library in assembly because there was a perceived performance problem in the library. While some more senior devs started the work on that, I profiled the library and saw that it was just one function call that was accounting for most of the performance problems. I also realized that this function call was being made 1200 times per second when we really only needed to make this call once and then we could cache that result. There is no point in putting in any sort of clever hack or optimization until you've identified a need for it. Most modern C/C++ compilers are pretty good at optimizing your code for you.

    36. Re:Such is C by beelsebob · · Score: 3, Insightful

      Wrapping it in ifdefs doesn't make it elegant. It just makes it not a hack. Instead, it makes it ugly, and correct.

    37. Re: Such is C by beelsebob · · Score: 0

      The only reason you would have that code still running on those chips is because it's not forward compatible with something more modern. Otherwise someone would have transitioned to some much cheaper, more recent, commodity hardware, and saved the business a lot of cash.

      That's definitely not good engineering, or something to brag about.

    38. Re: Such is C by wed128 · · Score: 2, Insightful

      The only reason you would have that code still running on those chips is because it's not forward compatible with something more modern.

      Or the bean counters don't want to pay the up-front cost of moving to something more modern. Many financial departments take a 'if it ain't broke' stance on computing hardware (and software!). many of them don't factor in electricity and maintenance costs, all they see is "$N Dollars for new server hardware? Why? That's rediculous!"

      It's why many COBOL programmers still have a job.

    39. Re:Such is C by Anonymous Coward · · Score: 0

      >For example in Python the claim is that there's almost always only one way to do something
      This is a complete and total lie. There may be one "good" way to do something (for values of good), but there are many ways of doing soemthing.

      Take, for instance, adding 1 to a list of ints. One can use a for loop and just add one, a list comprehension, or a generator wrapper that ingests a list and spits elem+1 back out. All of them have their drawbacks and pitfalls. Python, especially that ugly POS python 3, has just added more ways of doing the same thing in an effort to confuse anyone not drinking their koolaid.

      It's far, far better than PHP though.

    40. Re: Such is C by luis_a_espinal · · Score: 2, Insightful

      The only reason you would have that code still running on those chips is because it's not forward compatible with something more modern.

      Or because those platforms are running fine for the job they are required to do, and thus replacing them do yield any additional value? Proper engineering and business decisions call for changing things when you have to, when you have a reason, a valid reason.

      If it ain't broke, don't fix it is not just an empty slogan.

      Otherwise someone would have transitioned to some much cheaper, more recent, commodity hardware, and saved the business a lot of cash.

      Why cheaper? What if the hardware is already owned? What if the systems therein are running just fine as expected? If it ain't broke, don't fix it

      That's definitely not good engineering, or something to brag about.

      If it ain't broke, don't fix it. If you don't get it, you are not cut for this business.

      Do we go about rewriting all those lines of working-fine COBOL code into whatever is in vogue nowadays? Do you change your working-condition car every time a new model comes?

      The only time you change something is if you have a reasonable expectations of gains, or if the cost of keeping something that old goes above a certain threshold. Otherwise, you let it be.

      You know you are doing it right when your creation becomes legacy, and it runs unchanged for years, many years, providing value and ease of integration. That is, when the thing you created delivers value AND does not give reasons to decommission, then you know you did your job right, and you can brag about it.

    41. Re: Such is C by luis_a_espinal · · Score: 2

      The only reason you would have that code still running on those chips is because it's not forward compatible with something more modern.

      Or the bean counters don't want to pay the up-front cost of moving to something more modern. Many financial departments take a 'if it ain't broke' stance on computing hardware (and software!).

      That should be your reaction by default because change always incur costs and risks. So better have a valid reason to incur in new costs and risks. The operation of something old has to be costly, or difficult, or subpar, or the change to something new has a real chance of decreasing costs, or the change is part of a larger, business-related strategy. Only then you have a valid reason to change.

      many of them don't factor in electricity and maintenance costs, all they see is "$N Dollars for new server hardware? Why? That's rediculous!"

      The cost of electricity and maintenance costs may appear high, but if they are constant and well known, then they imply minimum risk. You can account them for (and you should if you are running a business, ... otherwise, don't run a business.)

      If maintenance costs are limited to hardware support, you can ignore them. If it is software costs in terms of difficult deployments or software upgrades, then yes, that is the threshold over which a change needs to be initiated.

      But if you don't have that, then, don't fix what is broken. Let the cost be constant and the risk known (and ergo manageable.)

      It's why many COBOL programmers still have a job.

      No. It is because most COBOL systems are running within expected parameters. After running for years, if not decades, they are well known, their features and their glitches. They are battle tested.

      And given the large size of these systems, it would be ridiculous to re-write them into something else. Why? Because that implies unknown risks and costs. Risk is something that grows exponential to the size of the re-write. This is not hand waving, this is a fact.

      There is more to software engineering than writing code. It also involves delivering solutions and values and managing risk. Software engineering must be seen as integral part of a business process. Otherwise, we are not software engineers, but mere code monkeys throwing shit at the wall, packaging and selling whatever sticks.

    42. Re:Such is C by khellendros1984 · · Score: 3, Informative

      This is a complete and total lie. There may be one "good" way to do something (for values of good), but there are many ways of doing soemthing.

      It's not a "complete and total lie." The Zen of Python, "Python Enhancement Proposal #20", states:

      There should be one-- and preferably only one --obvious way to do it.

      It's one of the guiding principles of the language's design. Type "import this" into a Python command-line, and PEP20 gets printed out.

      --
      It is pitch black. You are likely to be eaten by a grue.
    43. Re:Such is C by Anonymous Coward · · Score: 0

      Certainly if trivial stuff like (unsigned) -1 as a way to get max int bothers you, you'd probably feel more at home with high-level languages.

      Why not #include <limits.h> and use INT_MAX? It makes the intent perfectly clear.

    44. Re:Such is C by lgw · · Score: 2

      I remember that! It's why the C standard allows a void* to be bigger than an int* - char*s on Cray's needed extra bits for sub-memory-address-addressing.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    45. Re: Such is C by beelsebob · · Score: 0

      Why cheaper? What if the hardware is already owned? What if the systems therein are running just fine as expected? If it ain't broke, don't fix it

      Because when that existing hardware breaks, it'll be much more expensive to completely rewrite everything than it would have been to just keep it properly maintained all along.

    46. Re:Such is C by lgw · · Score: 1

      Yeah, sure I might use limits.h too, but that wasn't always dependably there, and it's one more #include with that many more lines of code to parse when compiling - stuff that used to matter.

      --
      Socialism: a lie told by totalitarians and believed by fools.
    47. Re:Such is C by fisted · · Score: 1

      A thousand times this.

    48. Re:Such is C by recharged95 · · Score: 1

      Poorly designed or obsolete languages:
      "do not reinvent the wheel because thou are not as wise as the wheel builder"

      Rightfully designed, efficient languages:
      "do not reinvent the wheel because you can be more efficient, and focus on behavior/app logic"

      The perfect case of C following the latter is the Linux Kernel--they do not reinvent a lot of things.

    49. Re:Such is C by Darinbob · · Score: 1

      A kernel always reinvents things. New file systems, new paging algorithms, new memory management. Maybe in applications you don't reinvent the wheel, but in low level code you do that often.

    50. Re:Such is C by Anonymous Coward · · Score: 0

      Yes, but only one of them will be the "pythonic" answer ;)

    51. Re: Such is C by Anonymous Coward · · Score: 0

      Definitely not if they're signed variables.

    52. Re:Such is C by dgatwood · · Score: 1

      Like I said, the minimum requirement is to break the build, so it won't be crashing, because it won't compile. The minimum requirement in a corporate environment is breaking the build plus an explanation of what the code actually does (if it isn't immediately obvious) so that when someone tries to manually enable it on a new architecture and it doesn't work, they know how to rewrite it generically.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    53. Re:Such is C by AceJohnny · · Score: 1

      For example in Python the claim is that there's almost always only one way to do something, which either means ugly hacks are not possible, or else there's a lack of imagination amongst the programmers.

      You're not being fair to Python.

      Python's specific mantra (as listed in PEP 20) is: There should be one -- and preferably only one-- obvious way to do it. Emphasis mine.

      Python, like any codebase, has a whole spectrum of "clean code" to "ugly hacks", but the richness of the language (and various libraries), provide a much richer foundation to let you avoid those ugly hacks.

      (Unlike Perl, where the richness of the language somehow seems to encourage ugly hacks ^_-)

      --
      Misleading titles? Inflammatory blurbs? Keep in mind that Slashdot is a tabloid.
    54. Re:Such is C by Anonymous Coward · · Score: 0

      You probably should always write a generic version without any hackish optimisations.

      If you're optimising hackishly then its probably a numerical computation and typical unit tests aren't really good enough to cover the behaviour of most such hacks. You will need to compare the output of a straightforward implementation that you can easily trust with that of the optimised version by using a large sampled data set.

    55. Re:Such is C by Anonymous Coward · · Score: 0

      Why the fuck would you willingly use shitty shit?

      It is not like a decent processor is expensive


      processor: 0
      vendor_id: GenuineIntel
      cpu family: 6
      model: 60
      model name: Intel(R) Core(TM) i5-4690 CPU @ 3.50GHz
      address sizes: 39 bits physical, 48 bits virtual
      processor: 1
      vendor_id: GenuineIntel
      cpu family: 6
      model: 60
      model name: Intel(R) Core(TM) i5-4690 CPU @ 3.50GHz
      address sizes: 39 bits physical, 48 bits virtual
      processor: 2
      vendor_id: GenuineIntel
      cpu family: 6
      model: 60
      model name: Intel(R) Core(TM) i5-4690 CPU @ 3.50GHz
      address sizes: 39 bits physical, 48 bits virtual
      processor: 3
      vendor_id: GenuineIntel
      cpu family: 6
      model: 60
      model name: Intel(R) Core(TM) i5-4690 CPU @ 3.50GHz
      address sizes: 39 bits physical, 48 bits virtual

      FFS You could get an 8 year old 3.0 Ghz core duo for basically nothing.

    56. Re:Such is C by Anonymous Coward · · Score: 0

      Reason # 6543543534 why functional programming is the way into the future.

      With a proper functional language, it never would have been called 1200 times a second.

  4. Maybe C developers are more honest by angryargus · · Score: 5, Insightful

    Regardless this seems like a pretty crappy study. There's many other phrases like kludge or XXX to have considered.

    1. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 5, Insightful

      C developers are good enough to know when what they're doing is an ugly hack.

      If PHP developers were at the same standard, every line would end with // Ugly Hack.

    2. Re:Maybe C developers are more honest by Dracos · · Score: 1

      Just WordPress developers. No, I take that back... WP devs are so shit that they wouldn't recognize any hack.

    3. Re:Maybe C developers are more honest by dgatwood · · Score: 5, Insightful

      C developers are good enough to know when what they're doing is an ugly hack.

      If PHP developers were at the same standard, every line would end with // Ugly Hack.

      I think the reason PHP is #2 on the list is that the people who are still writing PHP are mostly pretty good. The ones who were awful have all moved on to Python or Ruby or whatever the scripting language of the week is these days.

      In fact, I'd be willing to bet that a sizable percentage of the folks who are still actively using PHP are C programmers. I use it for all my web programming because it is exceptionally easy for me as a long-time C programmer. I basically write C with dollar signs and a few other minor tweaks, and it works. Even better, if there's some piece of code that has to be blisteringly fast, I can port it from PHP to C faster than you can say sed 's/\$//sg'. Okay, it really isn't quite that trivial, but it is pretty close.

      And yes, I do occasionally take advantage of being able to mix PHP and HTML, but not very often. I mostly just use it as a compile-free web programming language with better string handling and basic support for classes.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    4. Re:Maybe C developers are more honest by Anne+Thwacks · · Score: 1
      Another advantage of PHP is that the ugly hacks^H^H^H^H^H^H^H^H^H tricky operations are already written for you* - you just have to Google, and then invoke, the relevant library routine.

      * And in some cases, even tested too!

      --
      Sent from my ASR33 using ASCII
    5. Re:Maybe C developers are more honest by jandersen · · Score: 1

      Well, of course - it only counts how many occurences of a certain string you can find. An alternative interpretation could be that since people would have to know what beautiful code looks like in order to decide what ugly code looks like, there must be far more C programmers who know how to write good code. Which makes sense, I think; C is a language that allows the coder to make horrible mistakes, so in order to survive, you have to develop a coding style with strong discipline, which is what makes beautiful code.

    6. Re:Maybe C developers are more honest by delt0r · · Score: 2

      I like to personally use the phrase "A puppy dies every time this is executed"

      --
      If information wants to be free, why does my internet connection cost so much?
    7. Re:Maybe C developers are more honest by michelcolman · · Score: 1

      Next up, a new study detailing how many puppies are killed by different programming languages, based on the comments in the code.

    8. Re:Maybe C developers are more honest by mwvdlee · · Score: 1

      Or maybe they're simply aware of what is ugly and what is not.

      I develop PHP for a living and a while back I encountered a styleguide which said you should give function arguments. Code like 'function f($a, $a, $a) actually works in PHP. This in itself this as insane enough, but... some developers are retarded enough to require a styleguide to tell them not to do that. You think any of those developers will be able to tell the difference between an ugly hack and good, clean code?

      My guess is that most of this is just down to C developers generally having a better understanding of what is and is not ugly code.

      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    9. Re:Maybe C developers are more honest by mwvdlee · · Score: 5, Informative

      https://github.com/search?utf8...
      Javascript wins.

      PHP developers prefer murdering kittens: https://github.com/search?utf8...

      Some other fun facts:
      C developers are most ashamed of their code: https://github.com/search?utf8...
      PHP coder don't fix bugs: https://github.com/search?utf8...
      C developers' code actually get worse as it ages: https://github.com/search?utf8...

      Java developers seem to have the most trouble getting their code to work: https://github.com/search?utf8...
      Not surprising: https://github.com/search?utf8...

      Disclaimer; not corrected for any type of bias or error, of which there are many.

      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    10. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 0

      Tricky operations like comparing md5 sums, perhaps? (PHP wtf of the week these days)

    11. Re:Maybe C developers are more honest by Drethon · · Score: 1

      From what I've seen with Java and C#, the coders are less likely to understand they wrote an ugly hack. C on the other hand the coders tend to better understand their language and what is good and bad. One C# program I was working with stuffed everything into one massive class with a dozen tiny supporting classes. Took me forever to figure out what it was doing with all the duplication that could have been removed with proper inheritance.

    12. Re:Maybe C developers are more honest by stridebird · · Score: 1

      quick inspection of php known bugs returns a lot of identical code. Would be good to strip out the dupes...

    13. Re:Maybe C developers are more honest by IamTheRealMike · · Score: 2

      Haha, neat .... but ....

      Java developers seem to have the most trouble getting their code to work: https://github.com/search?utf8... [github.com]

      ..... that search is almost entirely results of the form:

      try {
      } finally {
          working = true;
      }

      So no, I don't think it shows anything about Java. If you want to get a similar string for Java I'd suggest variants on "TODO: Refactor this". Java has very powerful refactoring IDEs and the corporate world has more of an emphasis on constantly refactoring stuff (hey, it's less effort than debugging some stupid bug reported by marketing, right?).

    14. Re:Maybe C developers are more honest by ckatko · · Score: 2

      Some of my favorites:

      Dear God Why?
      https://github.com/search?utf8...

      Ugly as sin (Javascript wins, C a close second)
      https://github.com/search?utf8...

      "BUG" (Holy God, 52 million entries in C, Javascript has 5.4m in second)
      https://github.com/search?utf8...

      TODO (20.9 million C entries, 7 million on PHP in second)
      https://github.com/search?utf8...

      FIX (24 million C entries, 6.3 Javascript in 2nd)
      https://github.com/search?utf8...

      "Why does this work?" (C, 2.9 million, C++ 307,942 in 5th place)
      https://github.com/search?utf8...

      "What does this do?" (C, 10.9 million, C++, 1 million in 5th place)
      https://github.com/search?utf8...

      One would probably have to divide those results by actual number of files in that language to get a percentage. You also might want to control for code complexity. But if we were gonna be quick and lazy, I would guess C uses more hacks/obscure code to get the job done and when that veteran leaves, nobody knows what it does.

      On the bright side, C/C++ look like they tend to have tons of comments which (as long as they don't rot) is a very good thing. And if you're describing "why" and not "how" with comments, those will rarely rot.

    15. Re:Maybe C developers are more honest by Shortguy881 · · Score: 1

      WordPress developers - Isn't that an oxymoron

      --
      Brilliance without wisdom, power without conscience. Ours is a world of nuclear giants and ethical infants.
    16. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 1

      Interestingly, the very first hit on https://github.com/search?utf8=%E2%9C%93&q=%22why+does+this+work%22&type=Code&ref=searchresults is D code. And the sidebar on the left lists 0 D instances. So perhaps the language counters on github can't be trusted and all these "studies" are fatally flawed.

    17. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 0

      True True.. Runtime languages are an ugly hack in themselves, so if it isn't C, ASM or another base language compiled into machine code - 100% Ugly Hack.

    18. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 0

      Not to mention the lack of normalization to the number of files inspected...

    19. Re:Maybe C developers are more honest by O-Deka-K · · Score: 1

      Javascript developers think they're amazing (Javascript 760000, followed by HTML at a measly 323)
      https://github.com/search?utf8...

    20. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 0

      Shell scripts contain one or more ugly hacks per dozen lines of code.

    21. Re:Maybe C developers are more honest by Anonymous Coward · · Score: 0

      > Tricky operations like comparing md5 sums, perhaps?

      Yep. Just remember to use 'real_compare_md5_sums()'

  5. File this under "NO SHIT" by darkain · · Score: 5, Interesting

    Seriously guys. File this one under "NO SHIT" - Of course C is going to have the most ugly hacks. Why? Because it is by design able to access a hell of a lot more than other languages. How many languages have direct hardware access? Or inline ASM code? And does the word "hack" in the code really make it an "ugly" hack? Seriously? I wrote a micro-kernel for an ARM platform about a decade ago, and there was an assload of inline ASM code and direct pointer manipulation to access the underlying hardware, there is no other way to do this. Yeah, I'm sure the word "hack" appeared countless times in my code, because that's the general term we use. That doesn't make it "ugly" or bad by any means.

    1. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      You have the same possibilities to access the hardware in C++.
      But a lot of things that are considered ugly hacks in one language is considered standard practice in others so I wouldn't consider this study as more than pointless clickbait and ignore it.
      Studying development-time, maintainability or bug-fixes would be better.
      Sometimes hacks are ugly because they are hard to read. If it's still more readable than a clean solution in the same or another language then the programmers idea of 'ugly' is incorrect.

    2. Re:File this under "NO SHIT" by x0ra · · Score: 2

      You should check those "hack" really, it's not worth the name "hack".

    3. Re:File this under "NO SHIT" by AmiMoJo · · Score: 5, Insightful

      Maybe the reason C has more is that the specific string "ugly hack" is more commonly used by C programmers. Languages like Javascript are really ugly and full of nasty hacks, but that's normal for them so no-one comments on it.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    4. Re:File this under "NO SHIT" by jmv · · Score: 2

      I would also add that the most common reason why people write "ugly hacks" is to make their programs fast. If you care enough about speed to put these ugly hacks in your program, you're certainly not going to write it in Java or Python.

    5. Re:File this under "NO SHIT" by user317 · · Score: 1

      > I wrote a micro-kernel for an ARM platform about a decade ago, and there was an assload of inline ASM code and direct pointer manipulation to access the underlying hardware, there is no other way to do this.

      thats not an ugly hack, thats awesome! ugly hack to me means adding side-effects. like making data structures global and using extern to pull them in across unreleated parts of the code because you are to lazy to write a proper interface, using preprocessor hacks to hijack functions, using sed to "fix" binaries, most if not all of libc...

      --
      me fail english? thats unpossible
    6. Re:File this under "NO SHIT" by I4ko · · Score: 2

      This one exactly. The non-C developers are in general ignoramuses and for them the ugly hack is modus operandi, not an exception. For the C developer that is an exception, so they can recognize it and mark it as such. .

    7. Re:File this under "NO SHIT" by someone1234 · · Score: 4, Insightful

      In this study, an ugly hack was determined by the string "ugly hack" appearing in code comments. It was a totally scientific study.

      --
      Patents Drive Free Software as Hurricanes Drive Construction Industry
    8. Re:File this under "NO SHIT" by DigitAl56K · · Score: 1

      For languages like JavaScript, it's such an easy/accessible/portable language I actually wonder what the breakdown is. Just like every other language there are people who are really proficient in JS and aware of good practices and design, but there are also people who are so used to learning from ugly hacks of others they may feel it's acceptable, or they just have so little background with good code they have no idea that half their program constitutes an ugly hack. C certainly has a higher barrier to entry and you'll often find yourself working with professionals rather than other amateurs, so ugly hacks are called out because as the developer you know it's bad and you know others will judge you for it if you hadn't acknowledged it yourself.

      Of course, in JS I'm sure there are a lot of ugly hacks due to ugly browsers. Naming no names, but you know, ones that can be used to explore the internet.

    9. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      In Matlab, I write write code all the time that has something like "% stupid hack" on the end.

      It is an ugly hack if it's a concession to the way the language inherently works? Matlab only understands or implements tensor algebra for scalars, vectors and rank (1,1) tensors. Thus an expression like rho_{i,j,k} = a_{i,j} * b_{j,k} - c_{i,j,k} * f_k, which should involve only a single 3D array, will inevitably involve at least three due to having to use ndgrid() or repmat() to expand a, b and f in order to perform elementwise operations (which ML does for any dimension because they're trivial to define in all dimensions).

      Stupid yes, but a *hack*?

    10. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      "Of course, in JS I'm sure there are a lot of ugly hacks due to ugly browsers. Naming no names, but you know, ones that can be used to explore the internet."

      Honestly, nowadays, and especially with HTML5 changes, it's Firefox that requires the most JS hacks. IE hasn't been the main Javascript or CSS layout problem for quite a few versions now.

    11. Re: File this under "NO SHIT" by Anonymous Coward · · Score: 1

      Per the summary, they specifically searched for "ugly hack", not "hack".

    12. Re:File this under "NO SHIT" by BlackPignouf · · Score: 0

      Why not? Java can be almost C fast, and Python can also be really fast with e.g. Numpy.

    13. Re:File this under "NO SHIT" by phantomfive · · Score: 0

      Languages like Javascript are really ugly and full of nasty hacks

      That is so true

      --
      "First they came for the slanderers and i said nothing."
    14. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      Kinda this, when a C programmer leaves a comment saying something is a hack, it's a warning that you need to think very hard when modifying that code. And often it's not because the code is 'bad' it's because the hax was the only thing possible. As in I have to do things this way because otherwise the hardware FIFO is going to run dry otherwise. This is because in C land you usually can't just force IT to give you a phater slice.

    15. Re:File this under "NO SHIT" by AaronW · · Score: 1

      I agree, that's not a hack. I work on bootloaders and need to directly access low-level hardware registers and whatnot on 64-bit MIPS processors. I only need about a page of assembly code to do things like set up part of the L1 cache as stack memory and initialize a few registers before switching to C code. For some of the registers that require assembly to access we have macros to hide it. I certainly don't consider it a hack. Even inline assembly isn't necessarily a hack since some things require it, such as atomic operations, dealing with caches and stuff like that.

      --
      This post is encrypted twice with ROT-13. Documenting or attempting to crack this encryption is illegal.
    16. Re:File this under "NO SHIT" by Anne+Thwacks · · Score: 2

      If that is your idea of fast, you must be one of the people who think 2 + 2 = 5 for large values of 2.

      --
      Sent from my ASR33 using ASCII
    17. Re: File this under "NO SHIT" by Anonymous Coward · · Score: 0

      For number of versions less than and approaching zero...

    18. Re:File this under "NO SHIT" by Capsaicin · · Score: 2

      [Y]ou must be one of the people who think 2 + 2 = 5 for large values of 2.

      Well obviously 2 + 2 never equals 5, duh!
      2 + 2 approaches 5 as the value of 2 grows ...

      --
      Better to be despised for too anxious apprehensions, than ruined by too confident a security. --Edmund Burke
    19. Re:File this under "NO SHIT" by Karganeth · · Score: 1

      You sound incredibly angry. How DARE someone make a script that counts instances of "ugly hacks". IT IS A DISGRACE TO POINT OUT THINGS WE ALREADY KNOW. HAVE THESE PEOPLE NO DECORUM?

    20. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      JavaScript is an ugly hack by itself.
      It has Perl type safety, C++ syntax consistency and Scheme semantics.
      Is that one equal sign, two, three?
      How much is "duck" + 1 + orange()?

    21. Re:File this under "NO SHIT" by BlackPignouf · · Score: 1

      Well, I'm mostly a Ruby programmer.
      So yes, Java and Python+Numpy are fast for me :D

    22. Re: File this under "NO SHIT" by michelcolman · · Score: 1

      They probably chose "ugly hack" because they couldn't figure out how to write a regexp that matched "hack" but didn't match "whack", "shack" etc.

    23. Re:File this under "NO SHIT" by Anonymous Coward · · Score: 0

      If you followed a coding convention and implemented known good algorithms, the code wasn't a hack but an implementation to solve the problem. Getting around compiler and hardware bugs on the other hand..

    24. Re:File this under "NO SHIT" by c · · Score: 1

      Because it is by design able to access a hell of a lot more than other languages. How many languages have direct hardware access? Or inline ASM code?

      Amen.

      As a rule of thumb, any code (in any language) that deals directly with hardware and doesn't have at least a few commented hacks should be treated with suspicion. It likely either doesn't work, the hackery is too subtle for mortals to comprehend, or the person writing the code is so clueless that they don't recognize when they've transgressed into writing horrible hacks.

      --
      Log in or piss off.
    25. Re:File this under "NO SHIT" by gstoddart · · Score: 4, Informative

      Honestly, for some of us "hack" means anywhere from "an inelegant but necessary workaround", to "a really awesome and unexpected use of something", to "defeating system security", or a clueless person bashing away at something they don't understand, or "something I just whipped up".

      GP is absolutely correct ... for many of us, "hack" is a very generic term.

      --
      Lost at C:>. Found at C.
    26. Re:File this under "NO SHIT" by fisted · · Score: 1

      How many languages have direct hardware access?

      How the hell can a language have "direct hardware access?". What's that even supposed to mean?

    27. Re:File this under "NO SHIT" by fisted · · Score: 1

      You generally don't directly deal with the hardware in userspace; what language is used is entirely irrelevant.

    28. Re:File this under "NO SHIT" by AceJohnny · · Score: 1

      assload of inline ASM code and direct pointer manipulation to access the underlying hardware


      struct reg_map {
        uint32_t reg1;
        uint8_t regbank[32];
        uint32_t filler[7];
        uint32_t reg2;
      } __attribute__ ((packed));

      struct reg_map *device = mmap(blabla);

      device->reg1 = 0x1234UL;
      uint32_t data = device->reg2;

      You should try it some time :)

      --
      Misleading titles? Inflammatory blurbs? Keep in mind that Slashdot is a tabloid.
    29. Re:File this under "NO SHIT" by tepples · · Score: 1

      "Direct hardware access" means that the language has been supplemented with intrinsics to perform things like memory-mapped input and output (MMIO). For example, many compilers extend the C language to define casting an integer to a pointer to create a pointer that, when derefenced, accesses a literal address. In these extended C dialects, you get things like this:

      #define DISPCNT (*(volatile uint16_t *)0x04000000)
      #define DISPCNT_BLANK 0x0080
       
      inline void disable_screen(void) {
          DISPCNT = DISPCNT_BLANK;
      }
       
      inline void enable_background(size_t layer) {
          if (layer >= 4) return;
          DISPCNT = DISPCNT & ~DISPCNT_BLANK | (0x100 << layer);
      }
       
      inline void disable_background(size_t layer) {
          if (layer >= 4) return;
          DISPCNT = DISPCNT & ~(0x100 << layer);
      }

  6. There might be a bit more to it. by hamster_nz · · Score: 5, Insightful

    C coder know a ugly hack when they see one, and when they write one.

    I would conjecture that nearly every line of Perl scripts is an ugly hack, so nobody bothers to add a comment... 8-)

    1. Re:There might be a bit more to it. by Anonymous Coward · · Score: 0

      Then think about HTML documents. How many of them contains ugly hacks to give desired result on different browsers? How many of them has this in the comments?

    2. Re:There might be a bit more to it. by Anonymous Coward · · Score: 0

      My exact thoughts. C programmers are useds to delving far under the hood and so know an 'ugly hack' when they create one. All it indicates is the programmer's thoughts, "I know this can be made more elegant, but it will take me a bunch of time to polish. We have a deadline to meet right now, so this will have to do."

    3. Re:There might be a bit more to it. by hughbar · · Score: 1

      I'm a Perl person, so biased. That said, I agree with an associated idea, only realistic, humble and experienced people will mark 'ugly hacks' as such. Many others, less experienced, ignorant or simply 'bad' won't even recognise them.

      I'd love to see standardisation across languages for FIXME and TODO too, then it would be easier to distinguish the two cases, where they ARE distinct.

      Actually there are a lot of very big Perl codebases, well written and commented [and some atrocious ones, like every other language].

      --
      On y va, qui mal y pense!
  7. Key Words put on resume by Anonymous Coward · · Score: 0

    How get C coder job.

    Experience: 45 years experience with ugly hack.

    1. Re:Key Words put on resume by x0ra · · Score: 1

      Really ? Most of those "ugly hack" are symbols visibility issues... Not worth a Senior position....

  8. There's an issue with this analysis... by liberza · · Score: 1, Redundant

    It doesn't take into account that with Perl and PHP, "ugly hack" is implied.

  9. The ultimate ugly hack? by hamster_nz · · Score: 5, Insightful

    Fast inverse square root (sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5f3759df) is a method of calculating x1/2, the reciprocal (or multiplicative inverse) of a square root for a 32-bit floating point number in IEEE 754 floating point format.

    http://en.wikipedia.org/wiki/F...

    Anybody got any better Ugly Hacks to share?

    1. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 5, Insightful

      Duff's device

      C's default fall-through in case statements has long been one of its most controversial features; Duff observed that "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against."

    2. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 1

      that is not an ugly hack. that is an iterative approximation from some magic starting number that happens to work well.

    3. Re:The ultimate ugly hack? by phantomfive · · Score: 1

      I don't know if that counts as a hack.....

      Right now I am working on a project with a 4,000 line function, related classes scattered across multiple projects so they can't compile easily, objects from the messaging library used throughout so it can't be easily un-coupled, objects whose purpose is unclear and don't make sense even when it becomes clear. Not to mention inefficiencies that mean it is several orders of magnitude slower than it would be if written in [any language, really, as long as the design is better].

      the whole thing is a hack. There is no one line that is a hack, because that is everything.

      --
      "First they came for the slanderers and i said nothing."
    4. Re:The ultimate ugly hack? by Cesare+Ferrari · · Score: 2

      float->int conversion used to be expensive on x86 processors due to default rounding modes from C, and lack of suitable built in rounding functions. Looking back, my code contained this handy function. Ugly hack or elegant performance improvement? I'd suggest that the difference comes down to comments, unit tests, and whether people die if it's got bugs ;-)

      #ifdef WIN32
              #ifdef ASSUME_ROUNDING // This method relies on knowing the rounding mode of the float processor // // It relies on it being set to round to nearest and offsets the value to // calculate a truncation
                      inline int convert(float f)
                      {
                              int i;
                              static const float half = 0.5f;
                              _asm
                              {
                                      fld f // f = f
                                      fsub half // f = f - 0.5
                                      fistp i // i = round(f)
                              }
                              return i;
                      }
              #else // Shift the bits in the double around so that the bits can be read directly as an int
                      inline int convert(double d)
                      {
                              const double D2I = 1.5*(double)(126)*(double)(126);

                              double temp = d - 0.499999999 + D2I;

                              return *((int*) (&temp));
                      }
              #endif
      #else // On Mac we just use the standard C conversion since it doesn't suffer the performance hit // as on PC
              #define convert(x) int(x)
      #endif

    5. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 0

      Rounding you say?


      inline int32_t fast_round(double x) {
              #ifndef NO_FAST_TRUNCATE

              const double MAGIC_ROUND = 6755399441055744.0; /* http://stereopsis.com/sree/fpu2006.html */

              union {
                      double d;

                      struct {
                              #ifdef BIG_ENDIAN
                              int32_t hw;
                              int32_t lw;
                              #else
                              int32_t lw;
                              int32_t hw;
                              #endif
                      };
              } fast_trunc;

              fast_trunc.d = x;
              fast_trunc.d += MAGIC_ROUND;

              return fast_trunc.lw;

              #else

              if (x < 0) {
                      return (int32_t) (x - 0.5);
              } else {
                      return (int32_t) (x + 0.5);
              }

              #endif
      }

      Another fun hack is the modulo 2 optimization for floating point that relies on precision loss.

      // Wrap around
              volatile float z = (x + 25165824.0f);
              x = x - (z - 25165824.0f);

      The following lines belongs to an ugly hack added specifically to get around the incorrect whitespace filter on slashdot.
      The error message in question is as follows:

      Your comment violated the "postercomment" compression filter. Try less whitespace and/or less repetition.

      Do not read past this point.

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

    6. Re:The ultimate ugly hack? by suutar · · Score: 1

      Eh. I don't have a problem with the fall-through. Interleaving the switch cases and the do/while makes me shudder.

    7. Re:The ultimate ugly hack? by Rockoon · · Score: 1

      IEEE 754 is not magical, and neither is working with the IEEE 754 format at the binary level.

      Those that think that its an "ugly hack" to do so are computer science illiterate. Like that other guy that thinks leveraging twos-complement is an ugly hack.

      Pretenders dont know what ugly hacks are. You are one of them.

      --
      "His name was James Damore."
    8. Re:The ultimate ugly hack? by Darinbob · · Score: 1

      But that's mostly a C implementation of unrolling, something that would be perfectly normal in assembler code. But then there are the programmers who in their effort to banish all forms of Fortran style spaghetti code reject anything that can't be easily reworked with IFs and WHILEs. It probably also horrifies some programmers who think it's premature optimization (if it's not yet the end of the world then it's too soon).

    9. Re:The ultimate ugly hack? by Hognoxious · · Score: 2, Funny

      Swallow your pride and just give up, Lennart.

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    10. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 0

      IEEE 754 is not magical, and neither is working with the IEEE 754 format at the binary level.

      No, it's nothing magical about IEEE 754. The ugly part is assuming non-specified part of the hardware or the compiler, for example that IEEE 754 is used.
      If we begin with the nitpicking C99 doesn't have much to say about IEEE 754.
      IEC 60559 is the recommended floating point standard. It is however not required that it will be used.
      Any C code making assumption about the binary format of floating points without first checking __STDC_IEC_559__ or checking that it is compiled for hardware that in other ways specifies the floating point binary format is an ugly hack.
      Even if you do check that, C does not require or specify that the floating point unit uses the same endianness as the integer unit. This is of particular concern when the floating point unit is a separate IC.
      Take for example this statement from the ISO/IEC 9899:1999 standard

      The values of floating operands and of the results of floating expressions may be
      represented in greater precision and range than that required by the type; the types are not
      changed thereby.

      This can easily get you in trouble if you assume that the value is a 32bit float. The compiler is free to keep the value in a register that has 80-bit precision for optimization purposes.

      On the other hand, if you compare it to other mentioned languages clauses like that doesn't exists.
      That is not to say that the same problems doesn't exists in those languages, just that the programmer has no way of finding out if something is a hack and possibly non-portable.
      The C programmer has the documentation necessary to mark something as an ugly hack. In a language that lacks a proper standard every non-integer operation could be an undocumented ugly hack.

    11. Re:The ultimate ugly hack? by michelcolman · · Score: 1

      They really ought to have done it the other way around: break by default, and use "continue" to fall through. It can indeed be useful sometimes, but in the vast majority of cases you want it to break, and forgetting that statement causes all sorts of trouble.

    12. Re:The ultimate ugly hack? by abies · · Score: 1

      For me XOR swap was always an example of hack which is extremly ugly if not commented.
      http://en.wikipedia.org/wiki/X...

    13. Re:The ultimate ugly hack? by swillden · · Score: 1

      They really ought to have done it the other way around: break by default, and use "continue" to fall through. It can indeed be useful sometimes, but in the vast majority of cases you want it to break, and forgetting that statement causes all sorts of trouble.

      Depends on the sort of code. There is lots of code that needs to handle, for example, large classes of error codes, and for 50 codes there may be only two or three sensible ways to handle them. Being able to have big lists of cases that nearly all fall through is very nice then.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    14. Re:The ultimate ugly hack? by swillden · · Score: 1

      These day's Duff's Device is almost always premature optimization, because compilers will unroll most loops for you. You should only use it after profiling to prove that the loop is a hot spot, and after benchmarking to prove that it actually improves performance. Even then you should include both implementations, selecting one by #ifdef, so you can periodically re-test, because eventually a new platform or new compiler or something will result in it no longer making a difference, or even being more expensive, if the compiler is cleverer than you.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    15. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 0

      // This ugly hack probably won't work on WIN32 ARM
      // The Surface tablet is an overpriced piece of shit anyhow

    16. Re:The ultimate ugly hack? by michelcolman · · Score: 1

      OK, I'll amend my position slightly: they should break by default (and continue as an explicit option) but you should obviously be able to provide a list of values instead of the ridiculous 50 consecutive "case 5:case 6: case 7:...". Better still, they might add ranges while they're at it.

      Oh well, I don't imagine them changing the standard for that any time soon, but one can dream...

    17. Re:The ultimate ugly hack? by Anonymous Coward · · Score: 0

      Umm. Dude? You're wrong. It is a hack, and a fairly ugly one.

      You are attempting to solve 1/(sqrt(x)). The non-hack way to do this is 1.0 / sqrt(x). This hack involves bit-casting a float to an int, bit shifting it (divide by 2) subtracting it from a magic constant (who the fuck knows?) then bit casting back to a float and running newton's method on it. It is completely and totally counter intuitive, has little to do with proper math, and doesn't give the correct answer. It's a hack. Get over it.

    18. Re: The ultimate ugly hack? by Anonymous Coward · · Score: 0

      Hahaha got em.

    19. Re:The ultimate ugly hack? by fisted · · Score: 1

      Are you sure you understand why Duff's Device works? You can't do that with a "range" case, even if they would exist

    20. Re:The ultimate ugly hack? by michelcolman · · Score: 1

      I wasn't talking about Duff's device anymore, just the general normal usage of switch statements and the fact that they fall through by default, instead of the more logical opposite choice of breaking by default and continuing only by choice with an explicit instruction. Someone replied that falling through was useful if a whole list of values needed the same treatment, but I think it would have been better to have a standard where a list of values (and possibly ranges) could be provided rather than a silly list of "case x:case y:case z:".

      Obviously, if you wanted to use Duff's device with such a modified switch syntax, every case label would need a "continue" to fall through explicitly.

  10. Ugly but beautiful by Anonymous Coward · · Score: 2, Insightful

    God I love C.

  11. Social scientists have the most stupid conjectures by Anonymous Coward · · Score: 0

    An analysis of science papers shows that the social scientists have the most stupid conjectures. This is based on estimating the relationship between the hypothesis being examined and the data presented.

  12. Super scientific by bangular · · Score: 1

    I realize the analysis is probably a little tongue-in-cheek, but this is probably the worst analysis I've ever seen. Nothing of use was gained...

    1. Re:Super scientific by tgv · · Score: 1

      You're right. Number of files? Comment language? Size? History length? Just a few parameters that seem to influence the likelihood with which "Ugly hack" appears. Nope, first a good model, then the analysis.

    2. Re:Super scientific by Darinbob · · Score: 1

      Nonsense, it distracted me from my humdrum existence for a few minutes.

    3. Re:Super scientific by Megane · · Score: 1

      Indeed. It only means that C programmers are more likely to know when they've used an ugly hack.

      --
      #naabhaprzrag, #sverubfr-000, #agi-fcbafberq, negvpyr[pynff*=' negvpyr-ary-'] { qvfcynl: abar !vzcbegnag; }
  13. Perl was last? by Okian+Warrior · · Score: 3

    Perl was last on that list?

    For those people who say that Perl coders only write incomprehensible gibberish, I say:

    BWA HA HA HA HA!

    1. Re:Perl was last? by Okian+Warrior · · Score: 2

      Perl was last on that list?

      For those people who say that Perl coders only write incomprehensible gibberish, I say:

      BWA HA HA HA HA!

      (To be fair, a more interesting statistic would be the percent of files in each language that contain ugly hacks.)

    2. Re:Perl was last? by Black+Parrot · · Score: 1

      perl is a write-only language. It's *supposed* to be incomprehensible gibberish.

      --
      Sheesh, evil *and* a jerk. -- Jade
    3. Re:Perl was last? by Anonymous Coward · · Score: 1

      For those people who say that Perl coders only write incomprehensible gibberish, I say:

      BWA HA HA HA HA!

      I can't tell if that is supposed to be a laugh or if that actually is valid Perl code.

    4. Re:Perl was last? by Anonymous Coward · · Score: 0

      Perl was last on that list?

      Obviously! After all, the comment "ugly hack" is completely redundant when applied to Perl code.

    5. Re:Perl was last? by Viol8 · · Score: 1

      Nice one :o) Wish I had mod points.

  14. Nonsense... by SlovakWakko · · Score: 5, Insightful

    The whole C language is one beautiful hack, scary at first but once you get to know it in some really messed up sw project you can't help but love it. The balance between freedom and structure is excellent.

    1. Re:Nonsense... by dunkelfalke · · Score: 1

      Really? Not in my experience. Have been developing embedded software in C for money for 10 years now. The more years have passed, the stronger my dislike of C grew. It was ugly enough for the 1970ies, but using the same tools in 2015 is insane, I think. It is like using a slide rule instead of a TI-84.

      --
      "It's such a fine line between stupid and clever" -- David St. Hubbins, Spinal Tap
    2. Re:Nonsense... by SlovakWakko · · Score: 1

      Aaaah, slide rules... sooo beautiful... :)

  15. Same comment all over the pages by Anonymous Coward · · Score: 1

    Check it out yourself:

    https://github.com/search?l=&q=%22ugly+hack%22+created%3A%3E%3D2013-01-01+created%3A%3C2015-05-01&ref=advsearch&type=Code&utf8=%E2%9C%93

    #include "complex.h"

    then it says ugly hack for uClibc
    since it does not support complex functions properly and they want ./configure && make && make install
    fail for such embedded C library

    Sounds more of a copy-paste issue to make configure fail for uClibc, then an actual problem with the C language in general.

    6 #include "complex.h"
    7 +#ifdef __UCLIBC__
    8 +#error ugly hack to make sure configure test fails here for cross until uClibc supports the complex funcs
    9 +#endif
    10 int
    11 main () { ... }

  16. Low hanging hack... by x0ra · · Score: 5, Informative
    Did any of you actually read the "ugly hacks" this is pretty low hanging stuff, not the evil pointer-arithmetics and language corner undefined behavior case type of hack...

    #ifndef __INCif_etherh /* Quick and ugly hack for VxWorks */

    // ugly hack because we don't have fscanf
    int fscanf(FILE* stream, const char* format, int* value)

    #else /* ugly hack to make it compile on RH 4.2 - WA */
    #include
    #endif

    /* ugly hack GRR */
    #if !defined(__GNUC__) && !defined(__common_include__)
    #define __attribute__(x) /* nothing */

    /* XXX argh, ugly hack to make stuff compile! */
    #define snprintf(BUF, SIZE, ...) sprintf(BUF, __VA_ARGS__)

    1. Re:Low hanging hack... by chiasmus1 · · Score: 5, Insightful

      After looking at those examples, it seems to me that C programmers can claim something is an "ugly hack" because it was not what they wanted or because someone else's code was messed up. The C code hacks where there because they could not see an elegant solution. Programmers for other languages probably do not even know that the code they are writing is ugly.

    2. Re:Low hanging hack... by Anonymous Coward · · Score: 0

      Maybe more C programmers are experienced enough to know what constitutes a hack.

      The younger generation uses younger languages and does not know what a mess they are creating.

    3. Re:Low hanging hack... by I4ko · · Score: 1

      Took the words right out of my mouth

    4. Re:Low hanging hack... by Anonymous Coward · · Score: 0

      It seems to me that most of the ‘ugly hacks’ in the C code in the study are actually interfacing other code and are in files that are used from C++ as well. It is hard to tell at a glance how many real ugly hacks in the project code itself would be left if these were disregarded, but the conclusion remains the same:

      This ‘analysis’ is no analysis, since the data wasn't actually studied and no controls for confounding factors were applied.

      The author should have gone through a sizeable fraction of the code to search for actual ugly hacks manually, see if those correlate with comment or code patterns, see if the statistics on the full set match his sample, if not, find out why not, and so on and so forth. But that would be real work, wouldn't it?

    5. Re:Low hanging hack... by Darinbob · · Score: 1

      Yup, they are trying to make portable code which is also efficient, and that's hard to do as pragmatics keep tripping you up. With a lot of other languages, the portability is generally easier because there are no compiler differences, no machine differences, no limited subsets available for smaller machines, or the community generally never worries about portability.

  17. Examples of ugly hacks? by wvmarle · · Score: 1

    I for one would love to see some examples of such "ugly hacks", and also how it should/could be done in a not so ugly manner.

  18. Heavy duplication by x0ra · · Score: 3, Insightful

    Every single page has many occurence of the same "ugly" hack. If the folks who did the study had an ounce of legitimacy, they would have filtered for all those duplicates. If they had actually been competent, they would have done an in-depth study of all those "ugly hack". Of course, at this point, the article would have been worthless, but hey, they got their first page on /. ...

    1. Re:Heavy duplication by The+Mysterious+Dr.+X · · Score: 1

      I don't know how many of the 181,000 were duplicates, but if each "ugly hack" had 10 duplicates, that would still leave nearly 16,500 "ugly hacks" to study in-depth. I can't imagine a scenario in which that would be a worthwhile use of however many years it would take.

  19. Only meaningful if weighted by blind+biker · · Score: 4, Insightful

    These numbers should be weighted to the amounts of code in the various programming languages on GitHub. There may be lots of C "codefiles" with the "ugly hack" string in them, but there probably is a lot of C code overall on GitHub, too.

    --
    "The agriculture ministry is not in charge of Gundam" - Japanese ministry official.
  20. No perl comments, because it's implied. by Anonymous Coward · · Score: 0

    Yeah. I went there.

  21. Define Ugly Hack by enter+to+exit · · Score: 3, Informative

    "Ugly Hack" very often means the programmer has done a smart thing, if not an exactly correct thing. Although sometimes an ugly hack is just an ugly hack.

    1. Re:Define Ugly Hack by DrVxD · · Score: 1

      According to the summary, it's where the string "ugly hack" appears in the code - so it would consider this comment (and yours) to be an "ugly hack"...

      --
      Not everything that can be measured matters; Not everything that matters can be measured.
  22. How many lines of code in each language? by Anonymous Coward · · Score: 0

    The numbers does not show anything unless we have a point of reference - such as how many lines of code does each of those languages actually contain?

    Lets say there are 200 million lines of C code -> 0.1% Ugly hacks.

    Number of repositories for comparison do not sound like a factor of comparison unless we also have a average number of lines for each project.

    1. Re:How many lines of code in each language? by sectokia · · Score: 1

      Exactly.... going on my gut of language popularity I'd say the worst is Text.

    2. Re:How many lines of code in each language? by x0ra · · Score: 1

      There is 8700 fork of the linux kernel. My local copy of 3.17.1 has about 17 Mloc, so just the linux kernel fork's are over 147 Gloc.

    3. Re:How many lines of code in each language? by x0ra · · Score: 1

      FWIW, just my local copy of the linux kernel has 15 occurrences of "ugly hack".

  23. it's a C idiom by bugs2squash · · Score: 5, Insightful

    "/* ugly hack to... */" is a modest expression of pride describing concise, functional, readable and elegant C code in the same way as the term "//elegant approach to..." in C++ describes some borderline-insane misapplication of the STL with the incomprehensibility of perl and the verbosity of java.

    --
    Nullius in verba
    1. Re:it's a C idiom by Anonymous Coward · · Score: 0

      My thoughts exactly. Most of the "ugly hacks" I've come across (or written) in C can be understood with a little patience, some gentle prodding and an understanding of how computers actually work (for example 2s complement arithmetic, pointers, and #ifdef tricks to allow for "peculiar" machine architectures).

      Some of the "elegant" C++ code I've seen, on the other hand, is essentially impenetrable. Long-winded; often sprayed across a dozen different classes, files and headers; side-effects up the wazoo; *extremely* fragile in practically unpredictable ways; and often as not easier to replace (or at the very least fence off and avoid) than to maintain.

    2. Re:it's a C idiom by phantomfive · · Score: 1

      in the same way as the term "//elegant approach to..." in C++ describes some borderline-insane misapplication of the STL with the incomprehensibility of perl and the verbosity of java.

      rotfl

      --
      "First they came for the slanderers and i said nothing."
    3. Re:it's a C idiom by Darinbob · · Score: 2

      Someone I know has a fast way to compute CRCs without tables that use only a single loop. The method seems broken to some people who want to see the traditional nested loops, and they insist that the code must be wrong and so it should be rewritten to be larger and slower. They probably think it's an "ugly hack". But when you do the math it all works out.

    4. Re:it's a C idiom by Anonymous Coward · · Score: 0

      I don't doubt that this is possible but is it really faster than using tables on any actual existing processor? Even CRC-32 only needs a 1K table, it fits into cache, it's really fast unless you're doing CRC of very short strings. And is he perchance using his own non-standard polynomial to make this trick work? Has he proven that it's as strong as the standard polynomials?

      I'd be very interested to see the code :)

    5. Re:it's a C idiom by c · · Score: 1

      "/* ugly hack to... */" is a modest expression of pride describing concise, functional, readable and elegant C code...

      Speak for yourself.

      I usually use the expression "ugly hack" to describe the stupid shit I need to do to get around compiler or library bugs.

      --
      Log in or piss off.
    6. Re:it's a C idiom by fisted · · Score: 1

      "/* ugly hack to... */" is a modest expression of pride describing concise, functional, readable and elegant C code...

      Speak for yourself.

      I usually use the expression "ugly hack" to describe the stupid shit I need to do to get around the consequences of relying on unspecified or undefined behavior in my code.

      FTFY

    7. Re:it's a C idiom by c · · Score: 1

      I've been coding in C long enough to know the difference between unspecified/undefined behaviour and bona-fide bugs.

      For example, I'm pretty darn sure that a chunk of code such as:


      unsigned char inbyte;
      read(fd,&inbyte,sizeof(inbyte));

      should always read at most the same number of bytes (one byte would be nice, but let's pretend we're non-POSIX, here...). And if you *change* that chunk of code to something like, say:


      unsigned char inbyte;
      assert(sizeof(inbyte)==1);
      read(fd,&inbyte,sizeof(inbyte));

      It should *still* read at most the same number of bytes as the first chunk of code. If the second chunk of code reads 1 byte while the previous chunk of code was reading 2 bytes (and, incidentally, bashing the stack while dumping those 2 bytes into a 1 byte variable), I'm comfortable in calling that a compiler bug.

      Mid-late 90's Visual C++, in case you weren't aware, was not a good vintage.

      --
      Log in or piss off.
    8. Re:it's a C idiom by fisted · · Score: 1

      a chunk of code such as:


      unsigned char inbyte;
      read(fd,&inbyte,sizeof(inbyte));

      should always read at most the same number of bytes (one byte would be nice, but let's pretend we're non-POSIX, here...).

      I'm not sure I'm following. If we're non-POSIX, then what read(2) are we talking about? Also, that sizeof is by definition 1
       

      And if you *change* that chunk of code to something like, say:


      unsigned char inbyte;
      assert(sizeof(inbyte)==1);
      read(fd,&inbyte,sizeof(inbyte));

      It should *still* read at most the same number of bytes as the first chunk of code.

      Sure, although that assert is a no-op. It will never be wrong. If a no-op changes behavior of your program, then yes, it's either a compiler bug, or it's you having invoked undefined behaviour at some point and now the compiler doesn't need to hold on to its end of the deal anymore.
      I've seen too many "obvious compiler bugs" turn out to be no compiler bugs at all, so I tend to be careful with my conclusion.
      If that was indeed mid-late 90's MSVC++, then that makes it slightly easier to believe, yes ;)

    9. Re:it's a C idiom by c · · Score: 1

      I'm not sure I'm following. If we're non-POSIX, then what read(2) are we talking about? Also, that sizeof is by definition 1

      POSIX defines sizeof(char)==1. But C itself doesn't necessarily *require* sizeof(char)==1, just that char is the smallest non-bitfield type. Theoretically, sizeof(char)==4 could be legit on some architectures. In practice, I doubt there's a non-trivial C program on the planet that would function on such a platform, but it's there.

      The *point* of this being that the bug wasn't specifically that sizeof(char)==2, but that sizeof(char) was apparently variable within one trivial function in thousands of lines of code, and that throwing a trivial assertion in front of it was enough to change the value back to what it was supposed to be.

      If a no-op changes behavior of your program, then yes, it's either a compiler bug

      Exactly. In this case, it was the optimizer losing its shit. I wouldn't try to diff optimized and non-optimized ASM output from the compiler these days, but at the time it wasn't too horrible.

      If that was indeed mid-late 90's MSVC++, then that makes it slightly easier to believe, yes ;)

      It was still better than g++ on the DEC Alpha around that same time, but that's setting the bar pretty low.

      --
      Log in or piss off.
    10. Re:it's a C idiom by Anonymous Coward · · Score: 0

      So you are using not clearly defined data types and the fallout of that is somehow the fault of other?

      Instead of coming up with your genius "fix" you might have better done including inttypes.h and using properly defined types.

    11. Re:it's a C idiom by Ambient+Sheep · · Score: 1

      Someone I know has a fast way to compute CRCs without tables that use only a single loop. The method seems broken to some people... [snip] ...but when you do the math it all works out.

      I don't doubt that this is possible but is it really faster than using tables on any actual existing processor? Even CRC-32 only needs a 1K table, it fits into cache, it's really fast unless you're doing CRC of very short strings. And is he perchance using his own non-standard polynomial to make this trick work? Has he proven that it's as strong as the standard polynomials?

      I first came across what I think was the grandparent's "hack" when writing code back in the 1980s for an 8085-based EPOS-terminal. With a total address space of 64KB (albeit we did have paged ROM and RAM to extend that), any but the smallest look-up tables were a ridiculous luxury.

      First time I saw the hack, I thought "you WHAT now?!" and so one bored Friday afternoon I followed it all through and bloody hell, yes, it worked. Kinda melted my head as to how on earth the (since-departed) author had come up with it, but it worked.

      We used it to calculate CRC-16-CCITT and CRC-16-IBM in both normal and reversed versions (four in total), so it seemed to be flexible enough to use any polynomial you wanted.

      I'd be very interested to see the code :)

      Sadly, although I probably still have the code (only slightly naughtily, since I was also the guy responsible for doing the backups, including offsite backups), it'll be on a 5.25" floppy somewhere, and a quick Google doesn't turn up anything I recognise... so you'll have to wait for another day.

  24. Stupid by Mantrid42 · · Score: 2

    If a solution is stupid and it works, then it's not stupid.

    1. Re:Stupid by swilly · · Score: 1

      Maxim 43: If it's stupid and it works, it's still stupid and you're lucky.

      Credit goes to Schlock Mercenary.

    2. Re:Stupid by hcs_$reboot · · Score: 1

      Hmm, a code is supposed to be read and maintained. Using ugly hacks whenever possible is more of a showing off attitude. You know the "I use ugly hacks to show how good I know C, and then I post it on github to reach as many people as possible" attitude.

      --
      Slashdot, fix the reply notifications... You won't get away with it...
    3. Re:Stupid by Darinbob · · Score: 1

      Don't confuse this with being too stupid to understand how it works.

    4. Re:Stupid by Anonymous Coward · · Score: 0

      // Stupid hack to prevent win32 min/max macros clobbering std:: namespace
      #ifdef WIN32
      #undef min
      #undef max
      #endif

      int i = std::min(3, 5);

      It's stupid in the sense that it's necessary to compile std::min and std::max, but it works because it's correct, not because I'm lucky.

  25. 4k by Princeofcups · · Score: 1

    How could "ugly hack" exist in perl code. Every single line ever written is an elegant beautiful hack, by design.

    --
    The only thing worse than a Democrat is a Republican.
    1. Re:4k by John+Bokma · · Score: 1

      Just grep the (locally) installed modules, there are plenty of occurrences of "ugly hack". Even my own Perl code uses this, but rarely.

  26. How do you tell if .h is C or C++??? by halfdan+the+black · · Score: 1

    I suspect that most search engines classify .h as a C file. In reality it could be either, and far and away the most common practice is for C++ to also use .h for header files.

    On in extremely rare cases have I seen anything other than .h for C++ headers. Once in a great while, I've come across .hxx (there used to be a company that wrote compilers for Windows shareware developers called Borland that used .hxx or maybe .hpp I think) On SGI, I think I've once or twice seen .hh

    1. Re:How do you tell if .h is C or C++??? by Xest · · Score: 1

      What an obscure description of Borland.

      They wrote compilers for Windows shareware developers? Really? just Windows shareware developers?

      It was the number one Microsoft platform C/C++ compiler through the 80s into the mid-90s. It had nothing to do with Windows, or Shareware through most of it's life, and the company still exists even if it is a shadow of it's former self.

      I don't recall Borland C++ or Turbo C++ ever forcing use of .hpp files or similar though, I always stuck to .h. I've seen .hpp in various projects, not compiler specific. It seems to be entirely a concious choice by developers whatever the platform from what I've seen.

    2. Re:How do you tell if .h is C or C++??? by Anonymous Coward · · Score: 0

      I've seen plenty of usage of .hpp (eg Boost), and the std C++ library just omits extensions altogether. From what I've seen, it's less common to use alternatives to .h in user code.

    3. Re:How do you tell if .h is C or C++??? by Anonymous Coward · · Score: 0

      On in extremely rare cases have I seen anything other than .h for C++ headers.

      Then you must have never used the following:
      - Boost C++ Libraries (.hpp extension)
      - Qt (no extension, similar to C++ standard library)

    4. Re:How do you tell if .h is C or C++??? by swillden · · Score: 1

      (there used to be a company that wrote compilers for Windows shareware developers called Borland

      I can see you're a young'un. Borland didn't make "compilers for Windows shareware developers", Borland was the dominant maker of high-quality Pascal, C, and C++ development tools for the PC platform for many years, for DOS and Windows, especially DOS. Borland's overlay manager was fantastic and made large DOS programs (programs that used more than 640K) very easy. Microsoft eventually managed to shove them out, but Borland was by far the better tool set for years, and was the choice of many professional development shops. It's what the software companies I worked for in the early to mid-90s used.

      I think what eventually did them in was their decision to try to offer a better Windows API than that mess that was MFC. Borland's Object Windows Library was orders of magnitude cleaner and better thought-out than MFC, but because they had to wait for each release of Windows before they could update it, it lagged behind MFC in functionality. Probably also because the OWL team took the time to think about how to do things right, rather than just slapping a thin pseudo-OO wrapper on the Win32 API, which was MFC's approach. So Windows devs learned that if you wanted to stay current, you needed to use MFC, hence you may as well use Microsoft's whole tool set, since you had to buy it all (several hundred dollars).

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  27. Lack of data by Anonymous Coward · · Score: 0

    Yes, and how many files were scanned for each language. A proper analysis should show a comparison of the ratios not the absolute counts.

    If I had 100 C files in which 20 had "ugly hack" and 20 java files in which 10 had "ugly hack", obviously Java would be a bigger hit. And why stop at "files" ... perhaps you should be comparing occurrences per line of code or even file sizes.

  28. This academic exercise is useless by Anonymous Coward · · Score: 0

    If your not going to express the survey in a percentage of total of that language then this whole conversation is stupid. What if c has the most lines of code in the repository? Then of course it will take the top spot.

  29. Sponsored video?! by rastos1 · · Score: 1

    WTF! An autoplay video on frontpage? Slashdot, you have reached a new low ...
    Is it time for me to finally tick the "Disable Advertising" checkbox?

    1. Re:Sponsored video?! by Anonymous Coward · · Score: 0

      It's been like this for over 6 months and it's not just slashdot, I'm seeing autoplay video ads with audio at lots of sites all of the sudden. I've never had a desire to install adblock until now.

    2. Re:Sponsored video?! by fisted · · Score: 1

      It occasionally unticks itself.

  30. No ugly C# here by Anonymous Coward · · Score: 0

    This just goes to prove what we all know - that it is impossibly to write ugly code in C# ;)

  31. Self selecting? by Sarusa · · Score: 1

    Because C is so sparse and clean (or primitive, ymmv!), and people using C tend to be more experienced (almost nobody starts with C anymore - you use it because the job needs it), I find C programmers are a lot more likely to recognize things as ugly hacks and label them. It's partly defensive, because other C programmers are also old and cranky, so you're tagging it with YES I KNOW don't start with me. You don't want to check this in and have, say, Linus think you don't realize compromises were required.

    On the other hand, JavaScript people seem to be a lot more 'hey, doing this weird thing works without dying - I'll push it to production.' (YMMV, that's just my experience).

    1. Re:Self selecting? by DrVxD · · Score: 1

      that's just my experience

      No, really it's not. Plenty of us have experienced this...

      --
      Not everything that can be measured matters; Not everything that matters can be measured.
  32. Comments are subjective by Oligonicella · · Score: 1

    Which makes this all subjective. There are already comments by people who say that anything not done in C is ugly, so how to tell that these same people didn't pepper other's code with that statement? Many people think code is an ugly hack merely because it wasn't done the way they would code it.

    I've seen code written with procedures named for Alice in Wonderland characters and activities. Yet, I've seen that kind of thing defended here as 'creative'. 'Ugly hack' in a comment is a worthless indicator.

  33. C programmers know ugly when they see it by Anonymous Coward · · Score: 0

    Programmers in most other languages don't even notice.

  34. Question by Anonymous Coward · · Score: 0

    Were these taken in context?

    Was this about C hacks, game/os hacks, library work arounds, paradigm compensations, or just poor algorithm implementation hacks?
    The usage of comments such as this one is rather open to interpretation. C being considered a root language for many languages today may require "hacks" to get around such issues. Similarly implementations of things such as inline assembly, naked functions and goto statements are often seen as hacks, even though they are all perfectly fine when given certain considerations.
    To compound this issue, C is the lowest level language in the list of languages examined. There is a Huge issue with this as C becomes a choice language for development that requires low level access. For example drivers, IC's, and yes actual hacking. The problem with this is that C developers will often need to bend to the will of other systems they have little control over. Resulting in "ugly hacks", something that higher level languages often abstract away. Ever try implementing USB emulation on an AVR microcontroler? How about implementing red-black tree in C? Basically this article shows that a phrase shows up more commonly in the language, this phrase effectively means nothing at all. But may scare a few clueless employers into the thought that C is a poor language choice when it is one of the most powerful languages out there.

      Honestly, I believe further analysis is needed here before such a judgement is considered.

  35. Re:Social scientists have the most stupid conjectu by Anonymous Coward · · Score: 0

    That's because they aren't scientists at all. They're politicos looking to justify ideology.

  36. Of course it has the most ugly hacks by Khyber · · Score: 1

    And it has them for the same reason it has beautiful hacks:

    The complete and utter lack of fucking memory management, forcing the development of such hacks.

    --
    Still waiting on Serviscope_minor to wake up to fucking reality and realize that Jessica Price isn't going to fuck him.
    1. Re:Of course it has the most ugly hacks by Anonymous Coward · · Score: 0

      Of course, you didn't look into the nature of any of these ugly hacks and just assume they're to cope with C's meager memory management.

      It just sounds like C fucked the girl you were interested in but could never lay your hands on.

    2. Re:Of course it has the most ugly hacks by JustNiz · · Score: 1

      Don't blame the tool for your mistakes. There's nothing in C that forces anyone to write hacks.
      If you can only write write hack-free code when there's a garbage collector then you need to be looking for another profession.

    3. Re:Of course it has the most ugly hacks by Khyber · · Score: 1

      "Of course, you didn't look into the nature of any of these ugly hacks "

      I don't need to - most of the ugly hacks I've seen deal explicitly with the poor garbage collection that is built into C. Near infinite loops of del src() for shit like account logouts.

      --
      Still waiting on Serviscope_minor to wake up to fucking reality and realize that Jessica Price isn't going to fuck him.
    4. Re:Of course it has the most ugly hacks by fisted · · Score: 1

      Could you elaborate on what exactly is wrong with the C garbage collector?

  37. Ugly hacky? by Anonymous Coward · · Score: 0

    I have numerous phrases to describe a shitty solution but I have never used "ugly hack" once.

    Apparently I am a rockstar dev on Github or maybe just an ugly hack!

  38. Count of files invalid by Anonymous Coward · · Score: 0

    Percentage of files per language would be a more fair comparison. Maybe there's more C code than anything else.

  39. Film at 11 by Hognoxious · · Score: 1

    Coming up after the break, new insights into why dogs lick their balls.

    --
    Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  40. Alternative interpretation - C beset peer reviewed by Chrisq · · Score: 1

    Do we know that the comments were added by the author? An alternative explanation is that the C code has had fuller peer review than other languages, and the reviewer has marked these areas for future refactoring.

  41. Re:I like nubile girls by Anonymous Coward · · Score: 0

    Good thing we have Intel AMT/Vpro/VT.
    We will not check his computer for illegal bytes remotely.
    And then we will imprison him.

  42. Honest by snake_case_hoschi · · Score: 2

    Maybe C developers are just honest and experienced and name what it is.
    I won't accuse Java, with it patterns of patterns, when there is such a easy victim like PHP.

    PHP developers start their first line virtually with /* big hack */ and finish the last line with /* this is cruel */.

    1. Re:Honest by ledow · · Score: 1

      Or have higher standards and identify their ugly hacks where others don't?

    2. Re:Honest by aaronb1138 · · Score: 1

      Not to mention the potential ageism in the search criteria. C devs are naturally going to have an age and experience bell curve shifted years older than PHP or Java. This could mean the phrase "ugly hack" is more in keeping with the age range's vernacular. I'm sure the posers churning out PHP are more likely to comment /* omgwtfbbq */ and variations than the C group.

      Secondly, more experienced programmers and those working with more complex code, both things more likely with C than the other languages, are likely better able to identify what an "ugly hack" looks like. Lastly, C specifically lends itself to a lot of magic tricks for optimization that could carry "ugly hack" (e.g. the famous Quake Fast Inverse Square Root) which simply aren't worth implementing in other languages because they are too slow to matter.

  43. Not the fault of the coder? by Anonymous Coward · · Score: 0

    How often is the comment "ugly hack" part of a longer comment like: "ugly hack for Visual C workaround"?

  44. I don't think the stats are presented correctly by Anonymous Coward · · Score: 0

    I think the article is misleading, he should get the number of ugly hack per number of line or per number of files.

    Maybe there's 100x more js files than makefile hosted in github, thus it s a totaly different matter if it sum only 3x the number of hugly hack occurences.

    1. Re:I don't think the stats are presented correctly by marcovje · · Score: 1

      And per unique set of lines. Makefile and directories with js contains a lot boilerplate the same code.

  45. C is just more "hackable" by Anonymous Coward · · Score: 0

    I think the reason C came out on "top" is because C programmers are more conscious when they are doing something that the language doesn't accomodate natively but is flexible enough to get the job done and probably document this for their own sanity later on when revisiting that file.

    At some point on every project an implementer encounter a situation where they question whether a different language should have been used because of some intractable problem that ultimately gets solved with a "hack", that's what engineers do.. they make things work, sometimes having to use the tools and materials on hand...

    It's been my experience that in about 50% of hacks I've encountered or implemented was the result of poor design, 25% the result of language limitations, 25% the implementer was lazy and not wanting to fix the source of the problem and 25% due to not having time to fix the source of the problem (scheduling).

  46. The nature of comments by userw014 · · Score: 1

    I wonder if 'C' encourages or has a culture of having more comments than some of the other languages.

    And as other posters have hinted at when noting code that's trying to run in different environments, the environment C runs in (standard library, etc.) has varied longer (in time) and more (in versions) than the other languages mentioned. Seriously, is anyone writing new code for Ultrix anymore?

  47. Do a search for "MONSTER DONG"! by Anonymous Coward · · Score: 0

    I wanna know!

  48. It just shows the self awareness of C coders by 140Mandak262Jamuna · · Score: 3, Interesting
    They are just analyzing mostly comments, not code. Dijkstra gave the prescient warning ages ago: "Always debug the code, not the comment".

    C coders know when they are using ugly hacks and would take a moment to comment it or name the function with the term ugly hack. They realize it is not elegant and make a note so that future developers do not think it is a reference implementation worthy of replication and emulation. It is basically "this is probably not worth copy/paste, do a fresh implementation".

    Other language coders might be using these ugly hacks with pride not knowing anything better.

    --
    sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
  49. Slashdot has been reduced to Github search results by Anonymous Coward · · Score: 0

    It's a sad day.

  50. C? Ha! Upskilled ASM developers .... by Anonymous Coward · · Score: 0

    From, oh, at least a decade ago. My two, um, favourite ugly hacks found in cross-platform C++ production code have been:

    A file decompressor, obviously reverse engineered from a dis-assembly to C then wrapped in a C++ class, with all the variable name, abused do-for-while-if constructs and readability issues that implies. The main function was a 3000+ line switch statement finite state machine. The FSM was initialized by a goto jumping over half the function's variable declarations into the middle of a multiple page case statement buried halfway down the switch.
    IIRC there were also goto's jumping between bits of class member functions though that particular joyous bit of code reuse may have been found elsewhere.

    It had worked reliably for several years before being found. We made one change - the comment "Here be dragons"

    and

    A C++ class whose humungous private member variable section had two unused variables named _first and _last at the beginning and end of the section and whose constructor had "memset( &_first, 0, ( &_last - &first ) );" to initialize all the class member variables.
    We awarded this developer portability bonus points for not implementing their own faster memset() and adding the extra unused variables.

    Don't get me wrong these were extremely bright, experienced, developers who knew the internals of their chosen platform, dev tools and machine architecture from the metal upwards. All submitted code worked with very few bugs The code just occasionally needed hitting very hard with the +10 hammer of portability.

    Anonymous because I like working in the IT security industry.

  51. Perl: Great libraries, dead language. by Anonymous Coward · · Score: 0

    Perl is a write-only language.

    What was Perl originator Larry Wall thinking?

  52. Perl goes without saying. by Anonymous Coward · · Score: 0

    Perl is an ugly hack so all comments are unnecessary.

  53. C has the most of a lot of things by Anonymous Coward · · Score: 0

    C has the most algorithms: https://github.com/search?utf8=%E2%9C%93&q=algorithm&type=Code&ref=searchresults
    C has the most computation: https://github.com/search?utf8=%E2%9C%93&q=computation&type=Code&ref=searchresults
    C has the most tests: https://github.com/search?utf8=%E2%9C%93&q=test&type=Code&ref=searchresults
    C has the most characters: https://github.com/search?utf8=%E2%9C%93&q=characters&type=Code&ref=searchresults
    C has the most stuff: https://github.com/search?utf8=%E2%9C%93&q=stuff&type=Code&ref=searchresults
    C has the most things: https://github.com/search?utf8=%E2%9C%93&q=things&type=Code&ref=searchresults
    C has the most stupid: https://github.com/search?utf8=%E2%9C%93&q=stupid&type=Code&ref=searchresults
    C has the most smart: https://github.com/search?utf8=%E2%9C%93&q=smart&type=Code&ref=searchresults

    In conclusion, this article is very good and insightful, and in no way a complete waste of time.

  54. Meh. Could be a 'green' thing. by Anonymous Coward · · Score: 0

    I love new hardware. I spend a double digit % of my income on it.

    There is something to be said for people that get the full value out of the environmental impact required to produce their hardware. Right now I'm posting on /. I was doing this 10 years ago on, what is today, completely inferior hardware and it worked just fine. If someone kept that hardware alive and useful isn't that good engineering? Are people who restore/maintain classic cars not good mechanics because they should be working on a BMW-i?

  55. Statistics by Anonymous Coward · · Score: 0

    How many lines of code per language are they comparing here?

    phtt...

  56. I'll tell you what an ugly hack is by Anonymous Coward · · Score: 0

    Java. Thats an ugly hack.

    1. Re:I'll tell you what an ugly hack is by The+Mysterious+Dr.+X · · Score: 1

      I was sure you were going to name a coworker. Presumably an unattractive one with little applicable talent.

  57. Denominator? by Anonymous Coward · · Score: 0

    Did they even try to normalize the results to number of files? Lines of code?

  58. Not hack just hardcoding by Anonymous Coward · · Score: 0

    First, the counts are lame, searching a source repository is searching through all the version comments as well. If you filter only 'C' the first 10 pages are from 2 files in the same project.

    The vast majority are just hardcoding things, may be bad practice, but not really ugly hack. Most web scripting languages, PHP, JS, etc. people just do that. No reason to have header files or variable definitions like you would in C or other compiled languages that you wish to maintain well.
    True hacks would be like code that traps an error and ignores it because you have no idea why it's doing it, but it otherwise seems to work.
    catch(exception){ }

  59. 60bit processors by aberglas · · Score: 1

    Ever wondered why Pascal had packed arrays of char? It was for the Cyber, running 60 bit words. Did a fine job.

    C has the PDP 11 architecture baked into its soul, with 8 bit bytes being part of that.

    Worse, C has influenced all modern architectures to live within that crude model. For example, how could we have 64 bit pointers without using the upper 16 bits as tag bits? (No, we are never going to use them in our life times, memory access for that much memory would just be too slow. 32 to 64 bit is not the same as 16 to 32 bit.)

  60. JavaScript == and + behavior by tepples · · Score: 1

    Is that one equal sign, two, three?

    Both PHP and JavaScript define one as assignment, two as comparison after implicit conversion of values to the same type, and three as comparison of both type and value. Douglas Crockford, author of JavaScript: The Good Parts, proposes never using == at all in these languages, instead explicitly converting everything before comparing them with ===.

    Python handles it differently: one is assignment, two are comparison as defined by the types with fallback to is if not defined, and is is object identity (similar to Java == on objects). Python allows types to override operator == in much the same way that Java objects have an equals() method, and the built-in types do implicit conversions on numbers but little else.

    How much is "duck" + 1 + orange()?

    If you're going to overload operator +, there's a safe way and a less safe way. JavaScript performs the safer way of trying to convert things to strings. PHP, on the other hand, has implicit conversions biased toward numbers, which is why it doesn't overload +, instead using a separate concatenation operator.

    Here's how it plays out in JavaScript:
    1. Add parentheses on the left for infix operators of equal precedence: ("duck" + 1) + orange()
    2. If one side is a string and the other anything else, concatenation is used. "duck" + 1 becomes "duck" + "1" which is "duck1".
    3. "duck1" + orange() will also use concatenation.

  61. Not strictly conforming C by tepples · · Score: 1

    How many languages have direct hardware access? Or inline ASM code?

    A strictly conforming C program can't do either. Casting an integer to a pointer and dereferencing it is undefined by the International Standard, even if a particular implementation defines it to perform MMIO (memory-mapped input and output). Nor is asm a standard keyword. GitHub lumps C and C-as-extended-by-popular-implementations into one set.

  62. When optimization is not premature by tepples · · Score: 1

    It probably also horrifies some programmers who think it's premature optimization (if it's not yet the end of the world then it's too soon).

    It's not premature if it's documented properly. Algorithmic optimizations can carry a big O analysis, and micro-optimizations can carry before and after reports from your profiler.

  63. Your project has a debt problem by tepples · · Score: 1

    Right now I am working on a project with a 4,000 line function

    Even when coding in assembly language for an 8-bit microprocessor, I'd probably extract methods an order of magnitude before 4000 lines.

    related classes scattered across multiple projects so they can't compile easily

    Create a new project whose purpose is to provide classes to these projects.

    If your boss complains about not having time=money for refactoring, try first seeing whether your boss has heard of Dave Ramsey and his Total Money Makeover. If you're not familiar, Mr. Ramsey is a famous proponent of sacrifice to pay down personal debt. Then explain to your boss that your codebase is likewise deep in debt, and dealing with messy code like that is like having to spend a lot of your revenue on paying interest on that debt. Refactoring to pay the principal on your project's technical debt may delay getting the next feature out, but it might help you get the next six features out in same time that you otherwise would have produced only four.

    1. Re:Your project has a debt problem by phantomfive · · Score: 1

      I don't disagree with you, and actually I would clean stuff up without even telling my boss normally, I would just add a little extra time in all my estimates to clean stuff up. No need to get permission.

      The biggest problem right now isn't the code base, it's people. The people who created it are still around keeping it that way. They are the ones giving me pushback. Sample conversation:

      Me: "When a unit test breaks, we either need to fix it or disable it (if the unit test is no longer valid)."
      Others: "That's impractical. You can't always do that."
      Me: .......

      I've been struggling for months to help them improve their programming skills.

      --
      "First they came for the slanderers and i said nothing."
  64. Can your boss help you with them too? by tepples · · Score: 1

    If you're surrounded by co-workers who keep your team in debt, then you should work with your boss to start teaching them coding practices that will get your team out of debt.

    1. Re:Can your boss help you with them too? by phantomfive · · Score: 1

      My boss is one of the worst offenders. I've spent hours talking with him, trying to get him to understand good principles of programming. So far, the best I've gotten from him is, "your ideas are interesting, even when I disagree with you."

      Although he did reduce our 'standup' from 45 minutes down to 15 minutes..........

      --
      "First they came for the slanderers and i said nothing."
  65. F YEAH SEAKING (employment) by tepples · · Score: 1

    So your boss is part of the problem. Does your boss have a boss?

    Failing that: Do you have a Stack Overflow account? You might want to start posting answers there on your own time. By the time you get 1000 reputation or so, you should gain access to Stack Overflow Careers.

    1. Re:F YEAH SEAKING (employment) by phantomfive · · Score: 1

      Yeah, that's what I'm looking at. A few weeks ago, my request for a raise was denied (formally, because I wasn't mentoring enough.......which makes no sense given the amount of mentoring I've actually done).

      To me, that's the company saying they don't value me as an employee. No problem, I can find a company that does.

      --
      "First they came for the slanderers and i said nothing."
  66. I call bullshit by Anonymous Coward · · Score: 0

    Since the entire PHP language is a dirty hack and every line written in it is as well, PHP is the ugly hack champ by a wide margin.