Search code examples
c++cxcodecastingcalloc

How to build program without cast result of calloc in Xcode?


I'm trying to use calloc in my program. With an explicit cast it compiles and runs fine, but when I try to remove the explicit cast of malloc I see the following error:

Assigning to '... *' (aka '....... *') from incompatible type 'void *'

How can I compile my code without an explicit cast of calloc in Xcode?


Solution

  • You are attempting to compile your C code as C++.

    While it is true that some C code is also valid in C++, you have come across an example of C code that isn't valid in C++.

    That is, C++ does not offer the implicit conversions to/from void * that C does.


    You should always compile your C code using a C compiler, for the following three reasons:

    • You don't need to compile C code using a C++ compiler.
    • You're missing out on the best parts of C++.
    • You're missing out on the best parts of C.

    The only reason people try to compile C code with a C++ compiler is that they anticipate using their C code in a C++ project. However, this is unnecessary because you can usually compile your C code using a C compiler, compile your C++ code using a C++ compiler and then link the two together. For example:

    gcc -c c_code.c
    g++ -c cpp_code.cpp
    gcc cpp_library.o c_library.o
    

    In C++, it is generally a bad idea to use *alloc functions. Those who program specifically in C++ will usually cringe at *alloc use.


    In C, it is always a bad idea to explicitly cast void *, as the link you provided explains. Those who program specifically in C will cringe at unnecessary boilerplate that potentially introduces bugs.