Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d1211c6

Browse files
committed
Add macro to cast away const without allowing changes to underlying type.
The new unconsitify(underlying_type, var) macro allows to cast constness away from a variable, but doesn't allow changing the underlying type. Enforcement of the latter currently only works for gcc like compilers. Please note IT IS NOT SAFE to cast constness away if the variable will ever be modified (it would be undefined behaviour). Doing so anyway can cause compiler misoptimizations or runtime crashes (modifying readonly memory). It is only safe to use when the the variable will not be modified, but API design or language restrictions prevent you from declaring that (e.g. because a function returns both const and non-const variables). This'll be used in an upcoming change, but seems like it's independent infrastructure. Author: Andres Freund Discussion: https://postgr.es/m/20181015200754.7y7zfuzsoux2c4ya@alap3.anarazel.de
1 parent 2c300c6 commit d1211c6

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/include/c.h

+24
Original file line numberDiff line numberDiff line change
@@ -1121,6 +1121,30 @@ typedef union PGAlignedXLogBlock
11211121
#define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
11221122
#endif
11231123

1124+
/*
1125+
* Macro that allows to cast constness away from a variable, but doesn't
1126+
* allow changing the underlying type. Enforcement of the latter
1127+
* currently only works for gcc like compilers.
1128+
*
1129+
* Please note IT IS NOT SAFE to cast constness away if the variable will ever
1130+
* be modified (it would be undefined behaviour). Doing so anyway can cause
1131+
* compiler misoptimizations or runtime crashes (modifying readonly memory).
1132+
* It is only safe to use when the the variable will not be modified, but API
1133+
* design or language restrictions prevent you from declaring that
1134+
* (e.g. because a function returns both const and non-const variables).
1135+
*
1136+
* Note that this only works in function scope, not for global variables (it'd
1137+
* be nice, but not trivial, to improve that).
1138+
*/
1139+
#if defined(HAVE__BUILTIN_TYPES_COMPATIBLE_P)
1140+
#define unconstify(underlying_type, var) \
1141+
(StaticAssertExpr(__builtin_types_compatible_p(__typeof(var), const underlying_type), \
1142+
"wrong cast"), \
1143+
(underlying_type) (var))
1144+
#else
1145+
#define unconstify(underlying_type, var) \
1146+
((underlying_type) (var))
1147+
#endif
11241148

11251149
/* ----------------------------------------------------------------
11261150
* Section 9: system-specific hacks

0 commit comments

Comments
 (0)