In this question, someone suggested in a comment that I should not cast the results of malloc. I.e.
int *sieve = malloc(sizeof(int)*length);
rather than
int *sieve = (int *)malloc(sizeof(int)*length);
Why would this be the case?
In this question, someone suggested in a comment that I should not cast the results of malloc. I.e.
int *sieve = malloc(sizeof(int)*length);
rather than
int *sieve = (int *)malloc(sizeof(int)*length);
Why would this be the case?
In C you get an implicit cast from void* to any other (data) pointer.
It's optional. Typically you do the cast to avoid compiler warnings.
Marco
In C, you don't need to cast the return value of malloc
. The pointer to void returned by malloc
is automagically cast to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve
.
Casts are bad, as people have pointed out. Specially pointer casts.
You don't cast the result, since:
<stdlib.h>
.In C you can implicitly cast a void pointer to any other kind of pointer, so an explicit cast is not necessary. Using one may suggest to the casual observer that there is some reason why one is needed, which may be misleading.
As other stated, it is not needed for C, but for C++. If you think you are going to compile your C code with a C++ compiler, for which reasons ever, you can use a macro instead, like:
#ifdef __cplusplus
# define NEW(type, count) ((type *)calloc(count, sizeof(type)))
#else
# define NEW(type, count) (calloc(count, sizeof(type)))
#endif
That way you can still write it in a very compact way:
int *sieve = NEW(int, 1);
and it will compile for C and C++.
I like this explanation because it's throughout, talking about possible goodness and bad consequences: Casting.
This is kind of off topic, but a lot of people here I think are being a little harsh on casting. There are perfectly legitimate reasons to do it, like the following:
int x = 1;
int y = 2;
double z;
z = (double) x / (double) y;
Lest we forget our painful integer division bugs!