Can a float value be used as the index of an array? What will happen if an expression used as an index resulted to a float value?
-
A very bad idea because of rounding errors. However, sometimes this is useful, but then the value should be converted into integer first and bounds-checking (or limiting) be done before accessing. This operation can be useful e.g. for approximating values for a floating-point function using a lookup table.Tronic– Tronic2010-02-23 10:04:23 +00:00Commented Feb 23, 2010 at 10:04
5 Answers
Yes. But it's pointless. The float value will be truncated to an integer.
(You can use std::map<float, T>, however, but most of the time you'll miss the intended values because of inaccuracy.)
2 Comments
A C++ array is a contiguous sequence of memory locations. a[x] means "the xth memory location after one pointed to by a."
What would it mean to access the 12.4th object in a sequence?
1 Comment
This is an error. In [expr.sub]:
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type.
I am not aware of a clause in the standard that specifies that conversion should happen here (admittedly, I would not be surprised if such a clause existed), although testing with ideone.com did produce a compilation error.
However, if you're subscripting a class rather than a pointer — e.g. std::vector or std::array — then the overload of operator[] will have the usual semantics of a function call, and floating-point arguments will get converted to the corresponding size_type.