views:

83

answers:

2

Hey internets. I am having a VERY strange issue in C. I am deriving a float value, and then checking to see if it is greater than 0. However, the comparison is always evaluating to true, even if the value is less than zero. Here is the code:

if (sVel > 0.0f)
{
    sVel += 1.0f;
    sVel -= 1.0f;
    NSLog(@"SEP VEL: %1.6f", sVel);
    return;
}

So, setting sVel to 100 prints the log as expected and hits the return statement; cool. However, setting sVel to -100 does not print the log and still hits the return statement. I am utterly confused and I'm not sure where to start tracking this one down...

A: 

However, setting sVel to -100 does not print the log and still hits the return statement.

What return statement ? If sVel is negative, it should not execute anything. What comes after the fallthrough ? Are you sure its just not returning from the function ?

Tom
Hmm. I just cleaned my project and the line after the evaluation is now being hit. However, the debugger is still stopping on the `return;` line even though none of the other code inside is executed. More strange behavior from GDB...
Grimless
could you change that return for something else? For example "printf("formerly a return");"
Tom
@Tom: Perhaps as a test, yes, but for release no.
Grimless
yes, a test i mean.
Tom
+6  A: 

It looks like you are tracing the code using a debugger. Most compilers will probably optimize the code and the same return statement will be executed. It would appear then, that you are jumping to the return code regardless of the initial value of sVel.

The real proof is the print statement though. Since the log is not printed, that means, sVel was evaluated correctly. Try to put a log outside of the if block and see when it gets displayed.

hopia
Aha, that makes sense, I suppose. The debugger is stopping on the `return;` before hitting my other breakpoints which seems strange.
Grimless
" Most compilers will probably optimize the code and the same return statement will be executed " Exactly what I thought. Thats why I suggested on changing it for something else.
Tom