0

I know the differences between i++ and ++i (like this) if I want to use their new values. And I saw many examples in The C Programming Language (K&R) use expressions like s[i++] = c;. Sometimes, I come across codes (shown following) make me confused and this style seems highly regraded by them.

while (*string1++ = *string2++); //in c

And in this post, Jon 'avoid using' this style.

So my question is to use i++ (or ++i) like above code a good practice? If not, in which situation should I use it (Just when I don't use its new valve ?)

Community
  • 1
  • 1
Tony
  • 5,972
  • 2
  • 39
  • 58

2 Answers2

2

By itself, i++ is a clear, idiomatic expression for the idea of incrementing a variable. By itself, it is as clear as it gets. A computer language was named after this idiom (C++).

Jon wasn't saying to avoid "i++"; he was saying to avoid combining it with other expressions that would complicate things, where the increment operation was a "side effect". Like:

arr2[++j] = arr[++i];   // now what the heck is going on? I have to stop and look.

In that case, it is more reasonable to avoid it, and I agree with him. As you start to tweak code, and move things around, or add logic, the increment might go away, move, become redundant etc. and it is often better to perform the increment on a line by itself, or in a loop header instead.

The interesting thing about the ++ operator, besides that it Was a genius idea, is that the prefix and postfix alternatives encode more than just "i = i + 1", they encode an additional evaluation of the left or right hand side of the assignment, so to speak. (Or you could think of it as pre/post evaluation).

So ++i is functionally:

i = i + 1; return i

and i++ is functionally:

temp = i; i = i + 1; return temp

This difference causes additional "trouble" by hiding bugs, and you can see why, if the compiler doesn't optimize the generated code, they have different performance ramifications.

codenheim
  • 20,467
  • 1
  • 59
  • 80
0

It seems to largely be a matter of personal style and the requirements of the situation.

It's more concise to write i++ compared to i+=1 or i=i+1, and it can help you to remove lines of code that don't communicate an essential fact of the algorithm.

Of course, Jon Skeet is right (as usual) that it can make your code more difficult to understand: mentally distinguishing between ++i and i++ is another cycle your brain has to go through to understand what's going on.

There are situations where more granularity in your code is what you want; there are times when you don't care as much. There aren't really any hard-and-fast rules.

Of course, having said that, I would personally recommend not using i++ or ++i as function arguments (i.e. foo(i++)), since that can introduce some very hard-to-track bugs if you're not very careful, or mixing them with other operators (i.e. Bryan Chen's example of i++ + k++).

Jason Baker
  • 2,471
  • 3
  • 23
  • 28