简体   繁体   中英

How to understand this kind of function declaration?

谁能建议我下面的代码行代表什么?

static int(*pfcn[2]) (char *, ...) = { (void *)printf, (void *)NULL };

C gibberish ↔ English is a nice site that helps explain declarations

// declare pfcn as array 2 of pointer to function (pointer to char, ...) returning int
int(*pfcn[2]) (char *, ...)

{ (void *)printf, (void *)NULL }; initializes this array with the function printf() and then NULL , likely to to indicate the end.

int printf(const char *format, ...)
NULL

The static means the array is local and accessible only to the function/C file it is in.


@Lundin recommends which compiles well.

 // { printf, (void *) NULL };
 { printf, NULL };

IMO, also the declaration should be

//                    const added
static int(*pfcn[2]) (const char *, ...) = { printf, NULL };

Note: Some C may not allow casting a NULL to a function pointer. In that case code could use

static int printf_null(const char *format, ...) {
  return 0;
}

static int(*pfcn[2]) (const char *, ...) = { printf, printf_null };

... and test against printf_null rather than NULL to detect the end. Avoiding casts is a good thing.

pfcn is an array of function pointers.

The functions are those which take a variable number of args while returning an int .

It is a (hard to read) definition of an array of two functions. I would write it something like this:

#include <stdio.h>
#include <stdlib.h>

typedef int (*Function)(const char *format, ...);

static Function pfcn[2] = {printf, NULL};

The dots mean that the function will accept zero or more arguments after the first one.

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