Add macro M_CONST_CAST

This commit is contained in:
Patrick Pelissier committed 2017-05-26 12:40:37 +02:00
1 parent edb7ad2796
commit eaa8277f10
2 files changed
+23

No files matched your search

+11
View File
@@ -593,6 +593,17 @@
# define M_ASSIGN_CAST(type, n) static_cast<type>(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<const type*>(n)
#endif
/*
* From a pointer to a 'field_type' 'field' of a 'type'structure,
* return pointer to the structure.
+12
View File
@@ -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);
}