声明另一个函数时使用函数名和昵称(由 typedef 制成)有什么区别?

What is difference between using function name and nickname(made from typedef) when declare another function?

当我使用 typedef 中的名称时,出现了很多错误。但是在我将名称修改为原始名称后,它就可以工作了。我想知道他们有什么不同。

void SwapPoint(Point *pos1, Point *pos2);
//errors

void SwapPoint(struct point *pos1, struct point *pos2);
//it works


void SwapPoint(Point *pos1, Point *pos2);
typedef struct point
{
    int xpos;
    int ypos;
}Point;

void SwapPoint(Point *pos1, Point *pos2)
{
    Point temp;
    temp = *pos1;
    *pos1 = *pos2;
    *pos2 = temp;
}


there's no ')' in front of '*'
there's no '{' in front of '*'
there's no ';' in front of '*'

SwapPoint 的声明出现在 Point 的 typedef 之前,因此该名称尚不清楚。

将声明移到 typedef 之后:

typedef struct point
{
    int xpos;
    int ypos;
}Point;

void SwapPoint(Point *pos1, Point *pos2);

两个函数声明:

void SwapPoint(Point *pos1, Point *pos2);
//errors

void SwapPoint(struct point *pos1, struct point *pos2);
//it works

即使你为第二个函数声明写了"it works",在C中也是无效的。注意visual-studio编译器有很多错误,它自己的语言扩展不满足C标准.

第一个声明无效,因为名称 Point 尚未定义。

第二个函数声明无效,因为类型 struct point 在函数声明之外是不可见的,并且不表示在函数声明下方定义的类型。那就是参数类型和这个结构声明的不一样

typedef struct point
{
    int xpos;
    int ypos;
}Point;

来自 C 标准(6.2.1 标识符的范围)

  1. ... If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator.

因此将 typedef 放在两个函数声明之前。