Quote:Original post by Genjix
the thing is I forgot to say that the second if should only be evaluated when the first if is false.
Hence the "else if" in the suggestions.
Quote:
*** Source Snippet Removed ***
unfortunately analysing compiler output g++ doesn't seem to optimize that. so I tried
*** Source Snippet Removed ***
You do realize that these do different things, right? Let's consider z's value:
if c > 0
then in the first z == c
but in the second z == c if b <= 0 otherwise z == b
if c <= 0
then if b > 0 z == b in both, otherwise z is unchanged in both.
Now, let's consider a's value:
in the first, a == c no matter what.
in the second, if b <= 0 then a == b, otherwise a == c.
Also, g++ won't optimize the first form because it doesn't have the information you have. In particular, it has no way of knowing the second test will fail if the first succeeds (or that the body of the second will produce the same result as the body of the first, or whatever).
Quote:
This this function is called quite regularly it seemed like such a waste to be checking the second if statement.
Ya know, K&R were bright fellows. They saw this problem arising, and put in a keyword just to solve it. "else" ;)
By the way... "seemed like such a waste"? You did profile this before optimizing, right?
Quote:
Also b and c are gross over simplifications and are in fact complex expressions.
But yeah Magmai Kai Holmlor is the best I think if it's indented. But thanks all for your help. ++
Actually, if b and c are more complicated, I'd highly recommend against MKH's solution. It'll get ugly.