Question

I am writing a function that returns a pointer to an array of numbers. To be able to iterate over the numbers using a pointer I set the last element to NAN to mark the end of the array.
My Loop was something like

for(int* it=ptr;!isnan(*it);++it)  
//print *it

but it kept going until it crashed so I wrote some test code:

int* test = new int[1];  
*test = NAN;  
cout << isnan(NAN) << endl;  
cout << isnan(*test) << endl;

And the result was:

1
0

I have seen many examples for using NAN as a 'stopper' in arrays. So why doesn't that work?

Was it helpful?

Solution

You have undefined behaviour because you are attempting to convert NAN, which is of floating point type, to an int and that value cannot be represented by an int.

§4.9/1 [conf.fpint] A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

Since NAN is just a special value of floating point numbers, it doesn't make sense to store it in an int. Integer types don't have a special not-a-number value. You could use some specific value to denote the end of the array, but that's not a particularly pleasant solution.

If you're going to dynamically allocate your array like this, you are going to have to keep track of the size of it yourself by passing it around. For other arrays (where you actually have something denoting the array object itself, rather than just a pointer to its elements), you could use std::end to find the end of it. However, as usual, I suggest using standard containers instead.

OTHER TIPS

isnan() only works on floating point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top