简体   繁体   English

C99中的哪个规定禁止通过typedef定义函数?

[英]Which provision in C99 forbids definition of a function through typedef?

I know that a function definition can't be done through typedef. 我知道函数定义不能通过typedef来完成。 For example: 例如:

typedef int f_t(int x, int y);

f_t fsum
{
    int sum;
    sum = x + y;
    return sum;
}

But I can't find the provision which forbids this definition in C99. 但是我找不到在C99中禁止这个定义的规定。 Which provisions are related and how they forbid this definition? 哪些条款有关,以及它们如何禁止这一定义?

This is immediately given in the clause describing function definitions: 这在描述函数定义的子句中立即给出:

6.9.1 Function definitions 6.9.1函数定义

Constraints 约束

2 - The identifier declared in a function definition (which is the name of the function) shall have a function type, as specified by the declarator portion of the function definition. 2 - 在函数定义中声明的标识符(函数的名称)应具有函数类型,由函数定义的声明符部分指定。 141) 141)

141) The intent is that the type category in a function definition cannot be inherited from a typedef [...] 141)意图是函数定义中的类型类别不能从typedef继承[...]

The way this works is that under declarators (6.7.5), the only function declarators (6.7.5.3) are those with parentheses after the identifier: 这种方法的工作方式是在声明符(6.7.5)下,唯一的函数声明符(6.7.5.3)是在标识符后带括号的函数声明符:

TD( parameter-type-list ) TD( 参数类型列表 )
TD( identifier-list opt ) TD( 标识符列表选择 )

So, if the function is defined via a typedef then it does not have the syntactic form of a function declarator and so is invalid by 6.9.1p2. 因此,如果函数是通过typedef定义的,那么它没有函数声明符的语法形式,因此6.9.1p2无效。

It may help to consider the syntactic breakdown of an attempted typedef function definition: 考虑尝试的typedef函数定义的语法细分可能有所帮助:

typedef int F(void);

F f {}
| | ^^-- compound-statement
| ^-- declarator
^-- declaration-specifiers

Note that the typedef type F is part of the declaration-specifiers and not part of the declarator , and so f (the declarator portion) does not have a function type. 注意,类型的typedef F声明-符的一部分,而不是说明符的一部分,所以f (该声明符部分)不具有的功能的类型。

Since you're asking about the intent of forbidding typedefs from being used in a function definition (in some comments), the C99 rationale has this to say about it: 既然你在询问禁止在函数定义中使用typedef的意图 (在一些评论中),那么C99的基本原理就是这样说的:

An argument list must be explicitly present in the declarator; 参数列表必须明确存在于声明符中; it cannot be inherited from a typedef (see §6.7.5.3). 它不能从typedef继承(参见§6.7.5.3)。 That is to say, given the definition: 也就是说,给定定义:

 typedef int p(int q, int r); 

the following fragment is invalid: 以下片段无效:

 p funk // weird { return q + r ; } 

So it seems that the function defintion-by-typedef was disallowed because the definition didn't look enough like a function in that case. 所以看起来函数defintion-by-typedef是不允许的,因为在那种情况下定义看起来不像函数。

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

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