我并不是说这是一种好的编程风格,但是我很惊讶它编译后[*]并且运行时没有任何抱怨:
map
除了可能使人感到困惑之外,C标准中是否还有任何禁止使用相同名称的类型和形式参数的东西?
[*](在本例中为Apple clang版本11.0.0(clang-1100.0.33.8)。)
答案 0 :(得分:0)
我修改了代码,以检查名称proto_fn
是函数proto_fn
中的类型名称还是类型printit
的变量。
#include <stdio.h>
// define function signature
typedef int (*proto_fn)();
int x() { return 22; }
// Note: type name and formal parameter name are the same
void printit(proto_fn proto_fn)
{
printf("%d\n", proto_fn());
proto_fn;
}
int main() {
printit(x);
return 0;
}
上面的代码工作正常。
#include <stdio.h>
// define function signature
typedef int (*proto_fn)();
int x() { return 22; }
// Note: type name and formal parameter name are the same
void printit(proto_fn proto_fn)
{
printf("%d\n", proto_fn());
proto_fn kk;
}
int main() {
printit(x);
return 0;
}
但是此代码引发错误:
error: expected ‘;’ before ‘kk’
proto_fn kk;
因此,由此我得出结论,名称proto_fn
只是函数proto_fn
中类型printit
的变量。我认为类型proto_fn
在函数printit
内部不可见。我认为变量proto_fn
遮盖了函数proto_fn
内部的类型printit
。这可能就是代码起作用的原因。