Hacker News new | past | comments | ask | show | jobs | submit login

Although if you want your C to compile with a C++ compiler, you will need to cast the result of malloc(). C++ is more strongly-typed than C, and the compiler will complain.



You're right, that was an oversight. This is one of the more frustrating decisions in C++; it defies the semantics of a "void pointer", breaks existing code, and provides no real safety (the thing we're enforcing "type safety" over being a simple register-width integer used to express any type in the whole system).

But you do sometimes want to cut-paste code from .c files into .cpp files, and this idiom will make your compiler yell.


There are much more subtle differences that will wreak total havoc without the compiler emitting a single squeak. For example, compare this compiled as C or C++:

  #include <stdio.h>
  
  int foo;
  
  int main(void)
  {
      struct foo {
          int a, b;
      } x;
      printf("%zd\n", sizeof(foo));
      return 0;
  }
One should always write code in the best possible way for the language actually in use, even if this is invalid in some other language with superficially similar syntax. In converting code from C to C++, adding a few pointer casts will be the least of your worries.


One way implicit casts for void * are pretty big safety harness actually. You can still interpret any random pointer as "a register width thingamajig". Interpreting any random void * as a valid pointer to a particular type is obviously dangerous.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: