In general: Compiler optimizations are mostly done on the given source code. You're talking about optimization on run-time data, which compilers (normally) won't do. This means that you have to write these optimizations yourself.
In this case: You can indeed stop when there's a 0
.