简体   繁体   English

C typedef 定义的函数

[英]C typedef defined function

Within C how can I name a function?在 C 中如何命名函数? Just the name.只是名字。

typedef strlen StringLength fails to compile with: strlen does not name a type . typedef strlen StringLength无法编译为: strlen does not name a type

函数指针是一个解决方案

static Integer(*StringLength)(const Byte*) = strlen;

The correct way to "mock" a function - replacing the function call with another call - is to use #define . “模拟”函数的正确方法 - 用另一个调用替换函数调用 - 是使用#define If you also don't want to worry about parameters, then simply do:如果您也不想担心参数,那么只需执行以下操作:

#define StringLength strlen

Function pointers might work too, but they may be restricted to a certain scope, and you must get the parameter and return types right.函数指针也可能起作用,但它们可能被限制在某个范围内,并且您必须正确获取参数和返回类型。 For strlen specifically, the correct type is (C11 7.24.6.3):特别是对于strlen ,正确的类型是 (C11 7.24.6.3):

size_t strlen(const char *s);

Thus a correctly defined function pointer should look like:因此,正确定义的函数指针应如下所示:

size_t (*const StringLength) (const char*) = strlen;

Where the *const makes the function pointer itself read-only, which is good practice. *const使函数指针本身只读的地方,这是一个很好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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