8

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?

1
  • 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. Commented Feb 23, 2010 at 10:04

5 Answers 5

12

The float value will be casted to int (it can give warning or error depending on compiler's warning level)

s1 = q[12.2]; // same as q[12]
s2 = q[12.999999]; // same as q[12]
s3 = q[12.1/6.2]; // same as q[1]
Sign up to request clarification or add additional context in comments.

Comments

11

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

As for inaccuracy, I think there should be some way to provide your own compare function where you can include an 'epsilon'... a tolerance of sorts.
And of course you could also use unordered_map for more performance if the order doesn't matter. In this case you have to include epsilon in the hash function.
2

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

Note to pedants: yes, I know array offsets are not a simple addition of integers to pointers: this sentence assumes that a "memory location" is the size of an array member, so for an int a[], a[5] means the fifth word, not the fifth byte.
1

It will be casted to int.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.