Is it possible to rewrite the following code, so that it would be ISO C compliant ? The following macros are doing a malloc & init for a given type and value.
The current code works with the gcc compilers (uses a gcc extension), but it's not standard. If I use -pedantic, I receive warnings.
#ifdef __GNUC__
#define NM_CVPTR(type, value) \
({ \
type * var = NULL; \
var = nm_malloc(sizeof(*var)); \
*var = value; \
(const void*) var; \
}) \
#define NM_VPTR(type, value) \
({ \
type * var = NULL; \
var = nm_malloc(sizeof(*var)); \
*var = value; \
(void*) var; \
}) \
#define NM_PTR(type, value) \
({ \
type * var = NULL; \
var = nm_malloc(sizeof(*var)); \
*var = value; \
(type *) var; \
}) \
#endif
This can be done using the comma operator, but in standard C you won't be able to declare a variable as part of an expression, so you will have to pass the name of var
's replacement to the macro:
// C - comma operator but not able to declare the storage during the
// expression.
#define NM_PTR(type, var, value) \
(var = nm_malloc(sizeof(*var)), \
*var = value, \
(type * var))