for(int i=0;i<x;i++) is recomended?

Feb 17, 2011 at 4:09pm
Hello guys! I'm on Linux using GCC and i want know if is correct declare the variable inside the for hearder like it:

1
2
3
for(int i=0;i<x;i++){
    printf("%d\n",i);
}



Thanks.
Feb 17, 2011 at 4:12pm
In C++ the rule of thumb is to declare variables with as minimal scope as required. If "i" is to be used only by the for() loop and the code inside it, then it is quite right to declare it there.

C has different rules.
Feb 17, 2011 at 4:14pm
In C++, that's correct and desirable. But you don't need to save on whitespace. This is much more readable:

1
2
3
for(int i = 0; i < x; i++) {
    printf("%d\n", i);
}

And just so you know, the C++ way of outputting to the console is std::cout. You could replace that printf() line with this:

std::cout << i << '\n';
Last edited on Feb 17, 2011 at 4:14pm
Feb 17, 2011 at 4:21pm
While we're at it, also use ++i rather than i++.
Feb 17, 2011 at 4:34pm
.. What exactly would the benefit of that be?
Feb 17, 2011 at 4:54pm
Nothing unless "i" is an aggregate with a non-trivial copy constructor.

Implementation of post-increment for type T:
1
2
3
4
5
T operator++( int ) {
    T tmp( *this );   // We have to return the "old" value, so make a copy of the current state of the object
    ++*this;
    return tmp;
}


Clearly post-increment is slower since it does everything pre-increment does, plus more.

The simplest rule to remember is to use pre-increment unless you truly need post-increment, regardless of type.
Feb 17, 2011 at 5:15pm
You don't need brackets either if you only have one statement in the for loop.
Heck, you could even do this:
for (int i = 0; i < x; cout << i++ << '\n');
Last edited on Feb 17, 2011 at 6:53pm
Feb 17, 2011 at 5:59pm
You can write virtually any function as a single expression but that is not necessarily good.
Having the output in the body and the increment in the increment part of the for is much more readable.
Feb 17, 2011 at 6:39pm
Two questions:
Why does post-increment take an int? Where does that int come from?
Why isn't it defined to be the same as pre-increment except called after the end of the statement?
Feb 17, 2011 at 6:40pm
It takes a dummy int to differentiate it from the binary operator++ I believe.
Edit:
How would you code the operator to do something like that?
1
2
3
4
T operator++(int) {
    return *this;
    ++*this; // but make sure to do this after the expression is evaluated?
}
Last edited on Feb 17, 2011 at 6:42pm
Feb 17, 2011 at 6:50pm
It would be part of the language definition, not an optional thing.
both ++i and i++ would call the same function, at different times.
Topic archived. No new replies allowed.