Float Values ​​as an index in an array in C ++

Can float be used as an array index? What happens if an expression used as an index results in a float value?

+7
c ++
source share
5 answers

The float value will be passed to int (it may give a warning or error depending on the warning level of the compiler)

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] 
+10
source share

Yes. But this is pointless. The float value will be truncated to an integer.

(However, you can use std::map<float, T> , but most of the time you will miss the intended values ​​due to inaccuracy.)

+9
source share

C ++ - an array is a continuous sequence of memory locations. a[x] means "the place of the xth memory after it is pointed to a ".

What would mean access to the 12.4th object in the sequence?

+2
source share

It will be passed to int.

+1
source share

This is mistake. In [expr.sub] :

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions must be of type "pointer to T", and the other must have an unlisted numbering or integral type.

I am not aware of the condition in the standard, which states that the conversion should happen here (though I won’t be surprised if such a proposal existed), although testing with ideone.com caused a compilation error.

However, if you sign a class, not a pointer - for example, std::vector or std::array - then operator[] overloading will have the usual semantics of the function call, and floating-point arguments will be converted to the corresponding size_type .

0
source share

All Articles