Is it a better practice to typecast the pointer returned by malloc?

后端 未结 7 2181
闹比i
闹比i 2020-12-10 19:30

For the C code below, compare the defintions of the int pointers a and b;

#include 
#include 

int main()
{
  int *a=malloc(s         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 20:07

    Casting the return value of malloc() is a C++ idiom and has no place in C code. It's only necessary when you want to compile the code as C++, which you shouldn't do as C and C++ are distinct languages with diffrerent semantics.

    It only makes sense if you want to make a C library which defines inline functions in header files to be usable from C++. With the advent of link-time optimizations, this hopefully won't be necessary any longer as functions can be inlined even when defined in diffrerent source files.

    As to people claiming explicit casting adds to readability, consider the given example

    int *b=(int *)malloc(sizeof(int));
    

    How exactly repeating the type THREE TIMES is more readable than

    int *b = malloc(sizeof *b);
    

    is beyond me.

    C++0x even added type inference to get rid of similar repetitions, so I don't really think this is controversial.

提交回复
热议问题