> #define new(dtype,length) (dtype *)malloc(sizeof(dtype),(length))
Kind of a minor point, but isn't the consensus among C programmers that you shouldn't cast the result of malloc?
> #define new(dtype,length) (dtype *)malloc(sizeof(dtype),(length))
Kind of a minor point, but isn't the consensus among C programmers that you shouldn't cast the result of malloc?
a) is hardly an issue in a one-off macro definition, and b) is hardly an issue as you probably have #include <stdlib.h> just above the define. Besides, sane CFLAGS and any remotely modern compiler will protect you from b) anyway.
There is a minor benefit to casting in this case, as it will error out if I do:
int *x = new(x, 10); // should be new(int, 10)
because x is not a type.However, I still think this is terrible advice because it turns something very standard that every beginner C programmer understands into something that requires familiarity with the codebase and incurs a constant cognitive load. It also makes for some very hard to debug errors if I use "new" as a variable name somewhere. Not to mention total incompatibility with C++ due to choice of name.
The “don’t cast” consensus is about NULL remaining 0L and not of any pointer type (as was the case in some standard libraries in the early 90s)
Note also that the comma should be an asterisk.
int *x;
char *y = x;
or similar. But if x was "void*", it really should work on all C compilers.