C
Charlie Gordon
Harald van D?k said:If you would like a helper function such as:
static inline int *alloc_int(void) {
return malloc(sizeof(int));
}
but are implementing it as a macro:
#define alloc_int() malloc(sizeof(int))
not casting the result means you can assign it to a float * without any
diagnostic. I will admit that this is not a very common case though.
Types allocation macros can help make code more readable, without casts, yet
detect some mismatches.:
#include <stdlib.h>
#define alloc_type(type) ((type*)malloc(sizeof(type)))
#define alloc_array(type,n) ((type*)malloc((n) * sizeof(type)))
char *p = alloc_array(char, 100);
int *p = alloc_array(int, 100);
float *p = alloc_array(int, 100); // constraint violation