I’m looking for a way to only cast away volatility, without casting away the underlying type. I know about const_cast in C++, and I’m wondering if there is any equivalent way to do this in plain old C.
The problem is we’ve got some shared memory databases that are accessed through volatile pointers, and also a B-tree library that works with non-volatile pointers. (The tree will be locked during a find so it is fine for the compiler to not worry about the volatility within the B-tree library).
We also have a load of auto-generated code that links up the two, and casts away the volatile from the pointer. Unfortunately, today someone had defined the tree nodes using the wrong structure in the database, and that auto-generated cast completely hid the problem from the compiler.
It’s a bit tricky but you can get the preprocessor to help you here, if you only want to convert from pointer types to pointer types.
The basic trick here is that we force an assignment from
BartoFooin acv_castfromBar*toFoo*. This is done in the part after the,. It will trigger an error if and only if you are casting incompatible pointer types.However, note that
cv_casting pointers that point to invalid locations (e.g.NULL) will cause segfaults.Note: For reference (in the comments) this post used a helper function
nullfnpreviously that is not necessary. You can look it up in the history if you’re interested.