coderdave coderdave - 1 year ago 86
C++ Question

A cast that is breaking strict-aliasing rules

I have a function that takes a unsigned long* and needs to pass it to a external library that takes a unsigned int* and on this platform unsigned int/long are the same size.

void UpdateVar(unsigned long* var) {
// this function will change the value at the address of var
ExternalLibAtomicUpdateVar((unsigned int*)var); // lib atomically updates variable

This generate a warning saying that its breaking strict-aliasing rules. Are there any work arounds?

Thank you

Edit: I apologize for not being clear. The code is an atomic update so going around the library to store it is not an option. I could drop down to assembly but I'd like to do this in C++.

Answer Source
void UpdateVar(unsigned long* var) {
   unsigned int x = static_cast<unsigned int>(*var);
   *var = static_cast<unsigned long>(x);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download