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

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.
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.
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
While we're at it, also use ++i rather than i++.
.. What exactly would the benefit of that be?
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.
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
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.
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?
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
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.