Interesting. In one case the compiler must evaluate the if and remove it which leaves the assignment of val.
In the other with the assignment inside a loop it doesn't evaluate the loop control.
...