Catch up on stories from the past week (and beyond) at the Slashdot story archive

 



Forgot your password?
typodupeerror
Programming

Journal tomhudson's Journal: ++i vs i++ 28

I've seen people argue that you should make your loops like this:

for(i=0; i<10; ++i)

rather than

for(i=0; i<10; i++)

The "rationale" is that the compiler doesn't need to make a temporary with the pre-incremental form.

This didn't make sense with any modern compiler, as the compiler would recognize that both ++i and i++, in this particular case, can be assembled as "inc m/r" , with no need for a temporary.

Having to merge code using the two different forms (the "++i" version was written by a Windows weenie, and it really shows all over the code*), I decided to test whether there was in fact a difference in the final result. Running diff on binaries compiled using the two different forms says there is NO difference in the final emitted code.

* It really does show ... their code is strewn with all sorts of "optimizations" that make it unreadable and don't actually optimize anything. And then there's stuff like this:

if (SOME_CONSTANT != some_var)

rather than

if (some_var != SOME_CONSTANT)

Really - lets put it into plain english

This is not as understandable:

if 5 isn't equal to money_on_hand

as this:

if money_on_hand isn't equal to 5

The latter case is the preferred form in any sane universe, and a check with test code over 100,000,000 iterations shows no difference in speed, so there's another bogus "optimization" that's going to be removed.

... and the weird directory structure for both the source and output ...

... and using .cpp as an extension on a BSD system instead of .C for c++ source (at least there are no .hpp files) ...

... and yes, part of this is that infamous code I griped about last year that uses .ko as an extension for a non-kernel loadable object, rather than .so

... make files? only what we've added since ...

... and 3 different versions of /common, all populated by files with the same names and slightly different contents ...

... and the 3 different targets also all have the same names ... which is why there are 3 copies of everything that have "creeped away" from each other, all living in separate directory hierarchies ...

So, I've set up a separate svn repository on my machine, allocated 2 days to create a sane directory structure, fix the problems with the /common files, as well as the /modules that are really "almost the same" (they started life as identical), make some better make files, and get rid of the worst of the "odd stuff". Then the fun begins.

And if you're wondering how to set up svn quicky, I'll post a quick howto tomorrow that should get you running in 3 minutes.

This discussion has been archived. No new comments can be posted.

++i vs i++

Comments Filter:
  • if (SOME_CONSTANT != some_var)

    isn't an optimization, it's a programmer afraid he's going to write some_var=SOME_CONSTANT and screw everything up, so these days they teach you to put constants first so your compiler will smack you if you use = instead of ==.
    • if (CONSTANT == variable) {
      blah;
      }

      Was policy at a place I worked at a few years ago, for precisely that reason, and we used Linux almost exclusively.
      • by arb ( 452787 )
        I don't particularly care for that style, but if it is the shop's style then that's how I'll code. Personally I prefer the more logical if ( variable == CONSTANT ) {} because code should read well - besides, the compiler should issue a warning if I screw up and leave out an equals. Modern compilers are not dumb and will warn about messed up assignment/comparison operators.

        Elegant code approaches a prose-like quality, and this is difficult (if not impossible) to do with stylistic approaches like this. IMHO.
        • And don't forget about this (in Java)

          if("MyMagicString".equals(userInput) {
          doSomething();
          }

          To prevent erstwhile NullPointerExceptions. If nulls aren't expected or allowed, return an error code, don't let the NPE propagate. I seem to be the only one who does this, however.

          As for the i++ vs. ++i...I recently worked a developer who insisted that (again, in Java) you should use neither. i += 1 was the only way to go for this fellow. "That's how they do it a Google" was his rationale, and he insisted

          • by nizo ( 81281 ) *
            I like i+=1 better than ++i however. Ick.

            Then again, I prefer crap like:

            if (blahblahblah)
            {
                      stuff goes here
            }


            I just love the lonely braces :-) And I always enclose things with braces, even if it is only one line (saves time later when you want to add more stuff, plus it just seems more readable to me)
            • I've always preferred the lonely braces too, but it doesn't really matter any more. I haven't done much coding in years.
            • Gawd, I HATE lonely braces, and braces for single statements.

              I'd rather see perlish style than waste 4 lines where 2 will do.

              // my preferred
              for (int i=0; i<10; i++)
              j[i] += b[i-2];

              // a one-liner - the terminating ";" should be sufficient clue
              for (int i=0; i<10; i++) j[i] += b[i-2];

              In both cases, I'll leave a blank line above and below as a visual marker that "this is too a block!" With the horizontal screen space we have nowadays, there's no reason not to continue using real tabs (8 spaces)

              • by arb ( 452787 )

                Gawd, I HATE lonely braces, and braces for single statements.

                Whitespace is good - it improves readability and makes it a heck of a lot easier to find problems. As such, there is only one place for braces and that is on a line of their own as God intended.

                As for single statements enclosed in braces, this is a good thing because it makes it easier to add statements to an if/for/while/etc block without introducing bugs. (Of course, I only use braces for single statements about half the time - do as I say, not

                • "Whitespace is good - it improves readability and makes it a heck of a lot easier to find problems. As such, there is only one place for braces and that is on a line of their own as God intended."

                  Thank God I'm an atheist ;-)

                  I always put a newline before and after any flow control statement keywords such as if (), while (), switch () ... so the "braces improve readability" thing doesn't improve readability - it just makes for "line noise" 2 extra lines that do nothing. As for the "always put braces on

          • i++ should be compiled to inc m/r (where m/r) is either a memory address or a register. Ditto for ++i. The exception is if there is anything else that appears between sequence points in the statement - for example, instead of "i++;" you have "x = i++" or "x = ++i"; now you have a variable being incremented, and either its previous value being assigned to x, or its post-incremental value, so if the programmer hasn't had her morning cup of coffee, she may not realize that the cut-n-paste job (which is where

          • Meh, that sucks, imho, google be damned.

            If I was going to go that way, I'd go all the way back to the clunky (but more readable):

            i = i + 1;

            Constructs like +=, -=, *=, etc, aren't readable enough, when they're piled in with a bunch of different code.
            • "Constructs like +=, -=, *=, etc, aren't readable enough, when they're piled in with a bunch of different code."

              Don't laugh - I was putting in some white space to make just that look more readable.

        • With regard to if ( variable == CONSTANT ) {} as opposed to if ( CONSTANT == variable ) {}, why is one form more readable than the other? It's not like the equivalence operator has ever been anything other than reflexive. And it seems to me like the latter form actually is more informative - by writing the expression in that way (placing the possible lvalue on the right), the coder is specifically saying that the intent is not assignment.

          I don't really have a strong preference, though I tend to put the co
          • by Nevyn ( 5505 ) *

            why is one form more readable than the other? It's not like the equivalence operator has ever been anything other than reflexive.

            Because you don't say "yellow is my car colour", or even "is NULL my pointer". Sure, you can learn to speak backwards but it should be a last resort ... and GCC has a much better solution (has had for over 10 years, even).

            if (variable == CONSTANT) // Warning if assignment by accident

            vs.

            if ((variable = CONSTANT)) // No warning

            personally, I'd even prefer "no assignments

            • I suppose that's logical, at least in terms of English grammar. And it may well be that my exposure to other languages has made my understanding of essential structure a little more adaptable than yours. Or perhaps it was that HP calculator I had a while back. :-) But imposing the structure of English on a computer language seems odd to me, and a potential vehicle for misunderstanding.

              Would you find the same operand ordering more readable if the language was using postfix notation, rather than infix?

              I'm
            • Maybe its really Yoda-code. I can't believe this Yoda-code actually compiled and ran right the first time ... #include #define life 42== #define is /**/ int main() { if (life 42 is) printf("thanks for the fish\n"); else printf("the force is weak\n"); return 0; } Okay, I mixed Star wars and HHGTTG :-)
              • Aggh - slashcode ate my code!!!

                #include <stdio.h>
                #define life 42==
                #define is /**/

                int main() {
                if (life 42 is)
                printf("life is 42\n");
                else
                printf("nope\n");
          • by arb ( 452787 )

            With regard to if ( variable == CONSTANT ) {} as opposed to if ( CONSTANT == variable ) {}, why is one form more readable than the other? It's not like the equivalence operator has ever been anything other than reflexive. And it seems to me like the latter form actually is more informative - by writing the expression in that way (placing the possible lvalue on the right), the coder is specifically saying that the intent is not assignment.

            It reads better because it scans more like normal conversational Engli

            • It's been said that 90% of the cost of code is in maintenance. If the code is useful, its going to be reworked from time to time - and that costs money. If its buggy, it has to be fixed - and that costs money. If it needs new features, they have to be written and tested - and that costs money.

              Readable code is simply cheaper in the long run.

              Consistent indentation, consistent variable naming conventions, simple file layouts, and ease of reading all contribute to keeping the costs down and making every

        • Exactly. If code is less readable, its easier to hide REAL bugs. Anyone who still mistakes "=" and "==" after the first couple of years really should look for another line of work. You do it a few times when you first start out, spend an eternity wondering WHY something doesn't work right, then get a clue ... and since you've paid for that lesson with a lot of "wasted" time, the lesson is ingrained, and the time not really wasted after all.

          Of course, those who need such conventions because they can't

    • You're right ... that's the excuse I heard this morning. I really had to laugh. Then the guy explained that Microsoft teaches their coders to do it that way for that very reason. So I laughed some more. It explains why they have such a hard time remembering to type free(). The compiler won't nag if you don't ...

  • And Lo! Knuth said to the masses, "Premature optimization is the root of all evil." But the philistine coders, they did not listen, and clamored for more hand optimized code. Whereupon the Knuth smackethed them upside the head, and sayeth unto them: "Weren't you paying attention 10 years ago? Not only was it true then, but optimizers have gotten better!"

    Knuth, 594.

    OK, so maybe that wasn't a direct quote. But he was right then, and he's still right today. I recently had to rip out a bunch of crap co

    • Thanks :-) Actually, for my test method, I declared the variables before entering the loop, and set one of them based on a test for equality (as a flag), then return the flag at program exit, so the variables actually "hang around" (and changing the # of iterations has a definite, linear affect on total run time), but in your example, the whole loop definitely should be optimized out.

  • So, I'll admit that I prefer using ++num instead of num++ (and single letter vars are evil :). However it's got nothing to do with the compiler, I'd just assume any decent compiler would treat them equally (except maybe in some weird overloaded case in C++ ... but C++ is evil too :). The rationale is more that when you "are being clever" you are more often using the num++ variant, so not using that version when it doesn't matter draws attention to it when you do.

    The if (4 != foo) etc. is from people wh

    • All of us who wrote fortran before we learned c got into the habit of using i (and j and k) as loop counters. For small loops, its a pattern that everyone groks. For longer chunks of code, I'll use a symbolic name that communicates what I'm trying to do. for example:

      while (int node++ <= LAST_NODE) {
      ... lots of code ...
      }

      I try to make my logic so that my while loops increment their control variable immediately instead of at the bottom of the block - there were a few times I forgot to put that last "

  • th said...

    And if you're wondering how to set up svn quicky, I'll post a quick howto tomorrow that should get you running in 3 minutes.
    this should be good. i'm looking forward to learning it.
    • Actually, not ambitious - just a bit cheesed off that nobody bothered laying it out in a simple-to-follow step-by-step fashion.

      here you go [slashdot.org].

  • 10 for i = 1 to 20
    20 next i

    line numbers even.

Competence, like truth, beauty, and contact lenses, is in the eye of the beholder. -- Dr. Laurence J. Peter

Working...