Condition evaluates to true while debugger says it should be false
I was debugging in gdb when I came across this oddity:
(gdb)
107 newIterationRequired = infoAvailableUntil+1 < sqrt(input)+1 && isPrime ? TRUE : FALSE;
(gdb)
107 newIterationRequired = infoAvailableUntil+1 < sqrt(input)+1 && isPrime ? TRUE : FALSE;
(gd开发者_Go百科b) print infoAvailableUntil+1 < sqrt(input)+1 && isPrime ? TRUE : FALSE
$11 = FALSE
(gdb) s
108 if (newIterationRequired)
(gdb) print newIterationRequired
$13 = TRUE
newIterationRequired
's type is an enum that mimics boolean behavior from C++:
typedef enum { FALSE, TRUE } bool;
How is this possible?
GDB does not evaluate sqrt correctly as shown there: Why does gdb evaluate sqrt(3) to 0?
I would not rely on your (or gdb's) knowledge of operator precedence in this case. Try adding a couple of parentheses to ensure that you, the compiler, and gdb are actually seeing the same thing...
newIterationRequired = ( ( infoAvailableUntil + 1 ) < ( sqrt( input ) + 1 ) ) && isPrime
Oh, and a hint: Check out <stdbool.h>
...
Edit 1: Your comment says this didn't solve your problem.
Well then, pick the complex statement apart into its substatements. Store infoAvailableUntil + 1
into a temporary variable. Store sqrt( input ) + 1
into another temporary variable. Compose newIterationRequired
from those temporaries. From within GDB, check if the code, you, and GDB all agree on the outcome of each intermediate step.
This is elementary debugging. Pick apart the statement that is giving you trouble, reducing its complexity, until you have found the error or can ask a very precise question.
(Personally, my next "best suspect" is that your code and gdb see a different thing when you say sqrt()
.)
Unless you compile with -O0, you cannot be certain that the single stepping runs one line of source code after the other. It is possible that at the time you requested the expression evaluation, all arguments have not completed, so the result is not reliable.
Another explanation, is that some argument of the expression does not exists anymore in living registers, so gdb is fooled, and does a wrong computation.
精彩评论