Void pointer explanation

I've been learning about pointers lately, and I was curious about some special cases of (incorrect) usage of void pointers.


I made a code like this:
1
2
3
4
5
6
7
8
9
10
int main()
{
    float n = 5;
    void* myVoidPointer;
    myVoidPointer = &n;
    *(int*)myVoidPointer = 12;
    std::cout << n;

    return 0;
}


So, when I use the "*(int*)myVoidPointer" to change the value of the float data - what EXACTLY happens in the memory? Does it just change the first 4 bytes in the float, since the pointer is converted to int* before value assignment?

I know I am not supposed to use the pointers in this way, but I'm very curious! Cheers! =)
> So, when I use the "*(int*)myVoidPointer" to change the value of the float data - what EXACTLY happens in the memory?

The C++ standard has nothing to say about what could happen here; the entire program has 'undefined behaviour'
This International Standard imposes no requirements on the behavior of programs that contain undefined behavior.

A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).



> Does it just change the first 4 bytes in the float, since the pointer is converted to int* before value assignment?

Assuming that sizeof(int) is four bytes, that is what could happen in practice.
@ OP: Just thought that I would mention; if you're trying to manipulate the individual bits of a variable, on say a bitmask for example, then you'll want to look into the bit-wise operators or better yet, the std::bitset object: http://en.cppreference.com/w/cpp/utility/bitset
Topic archived. No new replies allowed.