How can I assign a float variable to an unsigned int variable, bit image, not cast

后端 未结 3 1017
无人及你
无人及你 2021-01-13 16:28

I know this is a bizarre thing to do, and it\'s not portable. But I have an allocated array of unsigned ints, and I occasionaly want to \"store\" a float in it. I don\'t w

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 16:39

    You can use reinterpret_cast if you really have to. You don't even need to play with pointers/addresses as other answers mention. For example

    int i;
    reinterpret_cast(i) = 10;
    
    std::cout << std::endl << i << " " << reinterpret_cast(i) << std::endl;
    

    also works (and prints 1092616192 10 if you are qurious ;).

    EDIT:

    From C++ standard (about reinterpret_cast):

    5.2.10.7 A pointer to an object can be explicitly converted to a pointer to an object of different type.Except that converting an rvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

    5.2.10.10 10 An lvalue expression of type T1 can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. That is, a reference cast reinterpret_cast(x) has the same effect as the conversion *reinterpret_cast(&x) with the built-in & and * operators. The result is an lvalue that refers to the same object as the source lvalue, but with a different type. No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.67)

    So it seems that consistently reinterpreting pointers is not undefined behavior, and using references has the same result as taking address, reintepreting and deferencing obtained pointer. I still claim that this is not undefined behavior.

提交回复
热议问题