Thread: Question about loops.

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    97

    Question about loops.

    Some people say that is more right to write
    Code:
    for(int i = 1; i < argc; ++i)
    than
    Code:
    for(int i = 1; i < argc; i++)
    What is the reason for that? (if that is true).

  2. #2
    The C-er
    Join Date
    Mar 2004
    Posts
    192
    Can't see it makes any difference. According to H&S 5 the result of the third parameter is discarded.

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    There is no difference. It's just a matter of style preference.
    If you understand what you're doing, you're not learning anything.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >What is the reason for that?
    Assuming the compiler takes you literally and doesn't implement an optimization that even Dennis Ritchie's first compiler used, the first is better because it avoids a temporary for the intermediate value. In theory, it's possible for i++ to be implemented like this:
    Code:
    int save = i;
    i = i + 1;
    return save;
    Whereas ++i can be implemented like this:
    Code:
    i = i + 1;
    return i;
    In reality, you probably won't see a compiler that fails to optimize both into the same machine code (for a standalone expression like the example). Miracle C might be one of those hypothetical bad compilers, but I don't know for sure because I avoid it like the plague.

    Use whichever you find clearer, but keep in mind that if you move to C++ there will be more of a difference because those operators can be overloaded. In such a case, it's better to use the prefix increment for class objects and whichever you want for built-in types.
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Oct 2003
    Posts
    97
    Thanks for the answers guys.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. noob question re: switch case & loops
    By scooglygoogly in forum C++ Programming
    Replies: 13
    Last Post: 08-25-2008, 11:08 AM
  2. question on GCD and for loops
    By dals2002 in forum C Programming
    Replies: 9
    Last Post: 03-15-2008, 01:59 AM
  3. question about while loops
    By volk in forum C++ Programming
    Replies: 4
    Last Post: 03-22-2003, 09:21 AM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM