Java and C# – Reasons for Post/Pre Increment Operators

cjava

Recently, I've stumbled across question about predicting the output of code which heavily uses post/pre increment operators on integers. I am experienced C programmer, so I felt like at home, but people made statements that Java just blindly copied that from C (or C++), and that this is an useless feature in Java.

That being said, I am not able to find good reason for that (especially with keeping in mind the difference betwen post/pre forms) in Java (or C#), because it's not like you will manipulate arrays and use them as strings in Java. Also, it was long ago when I last looked into bytecode, so I don't know if there's a INC operation, but I don't see any reason why this

for(int i = 0; i < n; i += 1)

could be less effective than

for(int i = 0; i < n; i++)

Is there any particular part of the language where this is really useful, or is this just a feature to bring C programmers in town?

Best Answer

is this just a feature to bring C programmers in town

It is surely a feature "to bring C (or C++) programmers in town", but using the word "just" here underestimates the value of such a similarity.

  • it makes code (or at least code snippets) easier to port from C (or C++) to Java or C#

  • i++ is less to type than i += 1, and x[i++]=0; is much more idiomatic than x[i]=0;i+=1;

And yes, code which heavily uses post/pre increment operators maybe hard to read and maintain, but for any code where these operators are misused, I would not expect a drastic increase in code quality even when the language would not provide these operators. That's because if you have devs which don't care for maintainability, they will always find ways to write hard-to-understand code.

Related: Is there any difference between the Java and C++ operators? From this answer one can deduce that any well-defined operator behaviour in C is similar in Java, and Java does only add some definitions for operator precedence where C has undefined behaviour. This does not look like coincidence, it seems to be pretty intentional.