0
double test = 0.0;
.... some code
char qwe = ...
.. some code
test += qwe;
if (test >= 200 || test <= 300) {
   test = 7.0;
}
// For some reason, test seems to equal 0?

Why does (test >= 200 || test <= 300) == false?

It's very strange behaviour.

And when I print the output, it's 0?

JamesSin
  • 39
  • 3

1 Answers1

6

Notwithstanding any undefined behaviour in your program, (test >= 200 || test <= 300) == false if, and only if, test is NaN. You can get a NaN (not a number) by some numerical error, such as 0.0 / 0.0 or by calling sqrt with a negative input.

Use std::isnan(test) to check for sure.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • May be, it's worth to mention that a NaN value has also another surprising behavior: It's the only value for which `f != f` is true. Because I wasn't sure about it I googled and even found this answer [SO: Checking if a double (or float) is NaN in C++](https://stackoverflow.com/a/570694/7478597) ...which is as short and precise as yours. – Scheff's Cat Nov 21 '17 at 10:54
  • 1
    @Scheff: Yes that does work, but compilers are increasingly optimising out that technique. – Bathsheba Nov 21 '17 at 10:55
  • Just to add: As the question mentions OpenCL in both title and tags, this might be in OpenCL kernel code. In that case, the function for testing for NaN is `isnan()`, as OpenCL doesn't have namespaces and a different set of built-in functions. – pmdj Nov 21 '17 at 13:12
  • 1
    Thanks for the answer Bathsheba, it was because of it being NaN. - OP – JamesSin Nov 22 '17 at 11:18
  • @JamesSin: Glad to be of help. You certainly will never forget the possibility. It's really vexing on first encounter isn't it? – Bathsheba Nov 22 '17 at 11:22
  • @Bathsheba Yup :D – JamesSin Nov 22 '17 at 12:01