0

For my exam I must be explain differences of the generic pointer (void *) in C and C++. They are two different things, but I can't find the differences between them.

hyde
  • 60,639
  • 21
  • 115
  • 176
Mitch
  • 87
  • 1
  • 9
  • 2
    To spice things up further, modern C also has `_Generic`. Maybe you could post a code example. – Lundin Aug 08 '19 at 14:06
  • "Unlike ANSI C, a generic pointer is not assignment-compatible with an arbitrary pointer type. This means C++ requires that generic pointers be cast to an explicit type for assignment to a nongeneric pointer value." [Link](https://www.ooportal.com/programming-cplus-plus/module4/generic-pointer-type.php) – lucidbrot Aug 08 '19 at 14:06
  • @NicolBolas I corrected it. Yew, it's the void * in C and C++ – Mitch Aug 08 '19 at 14:11
  • @lucidbrot thank you for your anwser – Mitch Aug 08 '19 at 14:15
  • The generic pointer type in C++ is `template using ptr_t = T*` ;) – NathanOliver Aug 08 '19 at 14:15

1 Answers1

6

In C, a void * pointer implicitly casts to any other pointer type. In C++, this cast must be made explicitly.

In C, malloc is used and we have Do I cast the result of malloc? (no); while in C++ malloc is frowned upon, the cast is required, but failing to include stdlib.h is a compile error. new returns the correct pointer type.

Other things went similar in C++; you shouldn't be downcasting void * much anymore. I only do it when interoping with C code or weird code optimization where template <class T> uses lots of T* and I can do most of the work in a non-generic base class (very rare).

However neither language quite has generic pointers. void * and void (*)() are not actually required to be the same size. void (*)() is used for the generic function pointer. In C, implicitly casting to/from it is a warning while in C++ this is an error. Most people cast explicitly in C because suppressing all "suspicious pointer conversion" warnings is a bad idea.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • that is the only one difference? – Mitch Aug 08 '19 at 14:15
  • 1
    Faling to include `` is an error in both languages. Though C was a long time a bit more tolerant, due to the late introduction of prototypes, shifting the exact error observed. – Deduplicator Aug 08 '19 at 14:22
  • Nit-pick. `void*` implicitly _converts_ to any other pointer type. A cast is an explicit conversion, made by the programmer. – Lundin Aug 08 '19 at 14:24
  • @Mitch: added remaining esoteric case. – Joshua Aug 08 '19 at 14:31
  • @Joshua Ehm. Yes, I *said* it was an error in both, though the exact manifestation is different. – Deduplicator Aug 08 '19 at 14:33
  • 1
    Consider reading "*[Are prototypes required for all functions in C89, C90 or C99?](https://stackoverflow.com/questions/434763/are-prototypes-required-for-all-functions-in-c89-c90-or-c99)*" for how things evolved in C. – Deduplicator Aug 08 '19 at 14:41