我并不是说这是一种很好的编程风格,但我很惊讶这已编译 [*] 并毫无怨言地运行:
#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());
}
int main() {
printit(x);
return 0;
}
除了可能会混淆人类之外,C 标准中是否有任何内容禁止对类型和形式参数使用相同的名称?
[*](在这种情况下,Apple clang 版本 11.0.0 (clang-1100.0.33.8)。)
最佳答案
我修改了代码以检查名称是否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
.这可能是代码有效的原因。
关于形式参数可以与类型同名吗? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057654/