简体   繁体   中英

Function Pointer cast at declaration

While looking for informations about calloc, I founded in the source code :

char *malloc();

in the calloc function.

Does it cast the void *malloc(size_t) into a function pointer returning a char* ?

This syntaxe does not compile for me.

In the old days, before ANSI C provides void * as the generic pointer type, char * was used for this purpose.

The code is from the source of Version 7 Unix , it's released in 1979 (before ANSI C ).

And this is the reason it's necessary to cast the return value of malloc() in the old pre-ANSI code .

Reference: C FAQ

That's from some very old source code. You're looking at code from UNIX Version 7, which was released in 1979. The C language has changed substantially since then.

It's not a cast; it's a function declaration. A cast consists of a parenthesized type name followed by an expression, such as (int)foo .

Furthermore, it's an old-style function declaration, a non-prototype that doesn't specify the type(s) of the parameter(s). (It's still valid syntax, though.)

It declares that malloc is a function returning a result of type char* . (It doesn't define the malloc function; that has to be done elsewhere.)

In modern C (since 1989), malloc return a result of type void* and has a single parameter of type size_t , so the declaration would be:

void *malloc(size_t);

but that declaration is provided by the standard <stdlib.h> header, so there's no need to provide the declaration yourself.

It's legal to have function declarations inside other functions, but it's seldom a particularly good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM