-3

Why does this happpens

double zero = 0.0;    
double a[] = { 0,0,0,0,0, zero/zero}; // NaN
cout << (a[5] == 5[a] ? "true" : "false") << endl;

prints

false
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Bharat Gaikwad
  • 530
  • 2
  • 5
  • 16
  • inspired from http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a – Bharat Gaikwad Sep 04 '13 at 07:34
  • 10
    IEEE xxx defines `NaN == NaN` to return `false`. – leppie Sep 04 '13 at 07:36
  • 6
    This is a completely pointless question. Why complicate things? – Jonathon Reinhart Sep 04 '13 at 07:38
  • @Jonathaon hey didn't got why it was happening so was asking – Bharat Gaikwad Sep 04 '13 at 07:39
  • 1
    @CoolEulerProject A comparison with a NaN always returns an *unordered result* even when comparing with itself – devnull Sep 04 '13 at 07:43
  • Hi all. I am not able to understand what is mean by the syntax 5a[]. a[5] is the value stored in 5th index of array 'a'. and simply a[] has the value of address of first element in array 'a'. – rakeshNS Sep 04 '13 at 07:57
  • 1
    I added the IEEE-754 tag. I'm getting a bit frustrated with people declaring "undefined behaviour" as soon as floating point is used. How many systems don't use IEEE-754 nowadays? I can imagine that some embedded low-end systems may not, but other than that? – Klas Lindbäck Sep 04 '13 at 08:04
  • 2
    I'm not sure why this has been closed, I thought it was a perfectly decent question. – Jack Aidley Sep 04 '13 at 10:38

2 Answers2

23

The compiler isn't getting it wrong, and it has nothing to do with a[5] == 5[a]. zero/zero is a nonsense expression and gets assigned NaN as a result but NaN != NaN because it can be produced in multiple non-equal ways.

Mind you, checking it out I think this is actually strictly undefined behaviour because the standard doesn't actually require the use of IEEE 754, or equivalent, floating point standards and can actually not support NaN. Where it does support NaN, section 7.2.14 (in the 2011 draft standard) requires that NaN comparisons return false.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
  • I haven't looked it up in the definition of double value interpretation, but I recall that any comparison to a value of NAN is defined as returning false. If you need to find out whether a value is NAN, there is a way to do that (I would have to google that, too). – SvenS Sep 04 '13 at 07:38
  • 1
    @SvenS - The preferred way is to call the `isnan` macro or function, but another is to check whether `x == x` returns false. – DocMax Sep 04 '13 at 07:43
  • 1
    I retagged the question as C++ because `cout << … << endl` was never C. – Pascal Cuoq Sep 07 '13 at 01:52
5

The issue is not a[5] vs. 5[a]. It is that NaN is never equal to anything, including itself. This gnu.org page has more details on comparing NaN and Infinity.

DocMax
  • 12,094
  • 7
  • 44
  • 44