Starting this series to describe code blocks that have tricked me at some point. Whether this be syntactic sugar gone bad or my own negligence, I hope to enlighten with these posts.
In the below code, we have a simple while-loop that sets x to the index of the first instance of the integer 5. If it doesn’t find 5, x will equal nums.length. If it does find 5, x will equal the index of 5 in nums.
int x = 0;
int[] nums = {0, 5};
while(x < nums.length && nums[x] != 5)
{
x++;
}
System.out.println("x = " + x);
Given this code, we would expect the program to print “x = 1”.
And this is exactly what happens… but let’s try some other examples.
int x = 0;
int[] nums = {0, 3};
while(x < nums.length && nums[x] != 5)
{
x++;
}
System.out.println("x = " + x);
Here, the program will not find 5 in the array and print “x = 2”.
Now, let’s say we want to make this code shorter. Let’s move the x++ into the while condition.
int x = 0;
int[] nums = {0, 3};
while(x < nums.length && nums[x++] != 5);
System.out.println("x = " + x);
Note that we moved the post-increment operator into the index operator.
And what do we get when we print this?
“x = 2”
That seems right!
But let’s try another example
int x = 0;
int[] nums = {0, 3, 5};
while(x < nums.length && nums[x++] != 5);
System.out.println("x = " + x);
Here, we would expect the program to print “x = 2”.
BUT it prints “x = 3”
Why is this?
This is because the post increment is in the check! Regardless of if the check is true or false, the increment will occur!
//So basically
while(x < nums.length && nums[x] != 5)
{
x++;
}
//does not equal
while(x < nums.length && nums[x++] != 5);