|
From: Bart V. A. <bva...@ac...> - 2014-10-22 15:04:20
|
On 10/22/14 14:55, Florian Krohm wrote:
> The other option is to replace the cast with some type punning trickery:
>
> #define CONST_CAST(T,x) \
> ({ \
> union { \
> const T in; \
> T out; \
> } var = { .in = x }; var.out; \
> })
>
> and use it like so:
>
> if (*s == c) return CONST_CAST(HChar *,s);
>
> I opted for the latter as it is less intrusive. The construct is
> guaranteed to work even with -fstrict-aliasing (which we're not using).
Hello Florian,
Does the above construct cause the compiler to generate additional code
compared to a regular cast ? Some time ago I introduced the following
construct in the Net-SNMP code base:
/**
* @def NETSNMP_REMOVE_CONST(t, e)
*
* Cast away constness without that gcc -Wcast-qual prints a compiler
* warning, similar to const_cast<> in C++.
*
* @param[in] t A pointer type.
* @param[in] e An expression of a type that can be assigned to the
* type (const t).
*/
#if defined(__GNUC__)
#define NETSNMP_REMOVE_CONST(t, e) \
(__extension__ ({ const t tmp = (e); (t)(uintptr_t)tmp; }))
#else
#define NETSNMP_REMOVE_CONST(t, e) ((t)(uintptr_t)(e))
#endif
Bart.
|