-1

Does the compiler(and here I'm thinking about gcc, but I guess it could be any C compiler) care about where a variable comes from? Why does it differentiate if the pointer comes from malloc? Is it just an optimization used by some compilers or is it mentioned in the C standard?

bsky
  • 19,326
  • 49
  • 155
  • 270

1 Answers1

4

unlike other (void *) pointers

Actually in C no void * needs casting, there is nothing special about malloc in this regard. You can convert automatically from and to void *, as long as you're dealing with object pointers (i.e. not function pointers).

or is it mentioned in the C standard


When do we need an explicit cast ? The standard says this:

6.5.4 Cast Operators

Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.

Forward to that section:

[...]one operand is a pointer to an object type, and the other is a pointer to a qualified or unqualified version of void [...]

So there you have it. No explicit cast required for void *.

cnicutar
  • 178,505
  • 25
  • 365
  • 392