'Do modern c++ compilers optimize assignments after type casting?

Take the following code:

char chars[4] = {0x5B, 0x5B, 0x5B, 0x5B};
int* b = (int*) &chars[0];

The (int*) &chars[0] value is going to be used in a loop (a long loop). Is there any advantage in using (int*) &chars[0] over b in my code? Is there any overhead in creating b? Since I only want to use it as an alias and improve code readability.

Also, is it OK to do this kind of type casting as long as I know what I'm doing? Or should I always memcpy() to another array with the correct type and use that? Would I encounter any kind of undefined behavior? because in my testing so far, it works, but I've seen people discouraging this kind of type casting.



Solution 1:[1]

AFAIK, a C compiler does not insert any code when casting a pointer - which means that both chars and b are just memory addresses. Normally a C++ compiler should compile this in the same way as a C compiler - this the reason C++ has different, more advanced, casting semantics.

But you can always compile this and then disassemble it in gdb to see for yourself.

Otherwise, as long as you are aware of the endianness problems or potentially different int sizes on exotic platforms, your casting is safe.

See this question also: In C, does casting a pointer have overhead?

Solution 2:[2]

If code performs multiple discrete byte operations using a pointer derived from a pointer to a type which requires word alignment, clang will sometimes replace the discrete writes with a word write that would succeed if the original object was aligned for that word type, but would fail on systems that don't support unaligned accesses if the object isn't aligned the way the compiler expects.

Among other things, this means that if one casts a pointer to T into a pointer to a union containing T, code which attempts to use the union pointer to access the original type may fail if the union contains any types that require an alignment stricter than the original type, even if the union is only accessed via the member of the original type.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mmomtchev
Solution 2 supercat