coderdave coderdave - 2 months ago 4x
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++.

void UpdateVar(unsigned long* var) {
   unsigned int x = static_cast<unsigned int>(*var);
   *var = static_cast<unsigned long>(x);