I recently had a discussion with a friend about code maintainability with regards to modifying an iterator inside of the body of a loop (C#
syntax):
List<int> test = new List<int>();
for (int i = 0; i < 30;)
test.AddRange(new int[] { i++, i++, i++ });
The code works fine, and as expected adds 0 - 29
into the list. However, he pointed out that the execution does look odd (and I agree), and told me about using Enumerable.Range(start, end)
. I have since switched to using the method and it works as needed.
During our discussion he stated that things like this cause issues with maintainability because it forces other developers to pause and examine what the intent is along with what is actually happening prior to making changes (we should all be doing this anyways in my opinion). He stated that things of this nature, aren't truly needed and should be refactored to a simpler version for that very reason. I do agree with this statement but he gave an example of obfuscation that we both agreed would not compile in C#
and is undefined behavior in C++
. I posted a question on StackOverflow but it was poorly received thus I believe it may be a better fit for here.
The code he wrote was:
int i = 2;
int c = i++ + ++((i++)++);
I tried to solve it using order of operations but I receive different results if I write it out by hand, and if I try to write it proceduraly in code:
int i = 2;
int p1 = i++;
int p2 = p1++;
int p3 = ++p2;
int c = i++ + p3;
The code above compiles in C#
and presume it would have no issues in most languages. This produces a result of c = 6
and i = 4
, however trying to solve by hand gives me c = 10
and i = 6
.
Can these issues be solved so the line i++ + ++((i++)++)
will compile and produce a sensible result? If so, what is the result of execution? Maybe there is already a major language (with C-style increment operators) where this works, which I am not aware of?
I've tried the following languages:
- C#
- C++
- Java
- JavaScript
31
instead of30
and let's assume the outcome is what theauthor
of the code intended - how many people will fail to see what he intended? That's rather the bomb some disgruntled developer would write before leaving the team.