diff --git a/m-core.h b/m-core.h index a85bad74..5fd8f82d 100644 --- a/m-core.h +++ b/m-core.h @@ -593,6 +593,17 @@ # define M_ASSIGN_CAST(type, n) static_cast(n) #endif +/* Cast 'n' of type 'type*' into 'const type*'. + This is like (const type*)p but safer as the type of 'n' is checked, + and more robust for double arrays type. +*/ +#ifndef __cplusplus +# define M_CONST_CAST(type, n) \ + (((union { type *ptr; const type *cptr; }){n}).cptr) +#else +# define M_CONST_CAST(type, n) const_cast(n) +#endif + /* * From a pointer to a 'field_type' 'field' of a 'type'structure, * return pointer to the structure. diff --git a/tests/test-mcore.c b/tests/test-mcore.c index 6aa2d02d..837e8cb9 100644 --- a/tests/test-mcore.c +++ b/tests/test-mcore.c @@ -208,6 +208,17 @@ static void test_oplist(void) assert (!CHECK_OPLIST (CLEAR_TOOT, M_DEFAULT_OPLIST)); } +static void test_cast(void) +{ + float f1 = 1.0; + float f2 = M_ASSIGN_CAST(float, f1); + int i1 = M_ASSIGN_CAST(int, f2); + assert (i1 == 1); + int *p1 = &i1; + const int *p2 = M_CONST_CAST(int, p1); + assert (*p2 == 1); +} + int main(void) { test_cat(); @@ -222,5 +233,6 @@ int main(void) test_va(); test_if(); test_oplist(); + test_cast(); exit(0); }