Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when explicit pointer type cast is needed?

In C, if I have two types of pointers:

typeB *q;
typeA *p; 

int the following, is it unnecessary to put an explicit cast (typeA *)

1    p= q       is fine, no need to use p = (typeA  *)q;

2    define: void func(typeA *p){}

     call:  func(q);  is fine, no need to use func((typeA  *)q)

3    p=malloc(sizeof(typeA));   is fine, no need to use p=(typeA  *)malloc(sizeof(typeA))

besides, is C++ the same or not?

thanks!

like image 227
misteryes Avatar asked Dec 04 '25 07:12

misteryes


2 Answers

I'll assume that they are unrelated types. If they are both aliases for the same type, then pointers to one can be implicitly converted to pointers to the other.

  1. No; in both languages, you need a cast to convert between unrelated pointer types. In C++, it is fine if typeA is a base class of typeB.

  2. Exactly the same as the first - both are trying to initialise a typeA* from a typeB*.

  3. Fine in C; void* can be implicitly converted to any object pointer type. That conversion is not allowed in C++; but you usually shouldn't be using malloc anyway.

like image 187
Mike Seymour Avatar answered Dec 07 '25 03:12

Mike Seymour


If you use TypeB * where TypeA * is expected, then you always need the cast. In C, there are two exceptions: conversion from and to void * is implicit (no cast needed) if the other type is a data pointer type. It's only under POSIX that void * is also implicitly compatible with function pointer types.

In C++, however, only conversion to void * is implicit, so assigning T *p = <expression of type void *>; still needs the cast.

Another difference is that in C++, if TypeA and TypeB are class (or struct) types, and TypeB inherits from TypeA then conversion from TypeB * to TypeA * ("downcasting") is again implicit (no cast needed). Of course this doesn't work backwards ("upcasting").

All in all, you don't cast the return value of malloc(), because:

  • in C is not required;

  • In C++ it would be required but in C++ you don't use malloc() anyway.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!