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.

170 of 264 comments (clear)

  1. 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. 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 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.

    11. 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...

    12. 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?).

    13. 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.

    14. 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.
    15. 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.

    16. 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...

  3. 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 x0ra · · Score: 2

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

    2. 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
    3. 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.

    4. 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
    5. 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. .

    6. 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
    7. 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.

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

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

    9. 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.
    10. 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
    11. 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
    12. 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?

    13. 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

    14. 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.

    15. 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.
    16. 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.
    17. 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?

    18. 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.

    19. 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.
    20. 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);
      }

  4. 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 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!
  5. 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.

  6. 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 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.

    6. 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."
    7. 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).

    8. 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."
    9. 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.

    10. 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...

    11. 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.
    12. 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.
    13. 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...

    14. 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

    15. 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.

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

    God I love C.

  8. 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; }
  9. 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 Viol8 · · Score: 1

      Nice one :o) Wish I had mod points.

  10. 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... :)

  11. 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 () { ... }

  12. 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 I4ko · · Score: 1

      Took the words right out of my mouth

    3. 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.

  13. 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....

  14. 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.

  15. 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.

  16. 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.
  17. 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.

  18. 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.
  19. 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.

  20. 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 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."
    2. 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.

    3. 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.
    4. 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

    5. 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.
    6. 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 ;)

    7. 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.
    8. 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.

  21. 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.

  22. 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.

  23. 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 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.
  24. 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.

  25. 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 fisted · · Score: 1

      It occasionally unticks itself.

  26. 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".

  27. 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.

  28. 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.
  29. 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)?

  30. 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.

  31. 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.

  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. Re:Such is C by Darinbob · · Score: 1

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

  34. 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.
  35. 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.

  36. 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.

  37. 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 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.

    2. 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.
    3. 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?

  38. 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."
  39. 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.

  40. 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
  41. 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 :-)

  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. 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
  44. 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.

  45. 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)

  46. 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.
  47. 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.
  48. 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);
            }
    }

  49. 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.

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

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

  51. 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?

  52. 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

  53. 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?

  54. 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.

  55. 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
  56. 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.

  57. 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.

  58. 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.

  59. 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.

  60. 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.

  61. 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.

  62. 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.
  63. 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.
  64. Re:carmack puts it best by PrescriptionWarning · · Score: 1

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

  65. 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.
  66. Re:Such is C by fisted · · Score: 1

    A thousand times this.

  67. 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.

  68. 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.

  69. 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.

  70. 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.)

  71. 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.

  72. 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.
  73. 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.

  74. 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.

  75. 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.

  76. 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."
  77. 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."
  78. 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."
  79. 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.