形式参数可以与类型同名吗? (C)

标签 c typedef

我并不是说这是一种很好的编程风格,但我很惊讶这已编译 [*] 并毫无怨言地运行:

#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/

相关文章:

c - 在 rand() 循环中分配随机浮点值时出现段错误

c - 如何漂亮地打印嵌套链表

c - 大小未知的 printf 和(带符号的)int

c - 堆内存澄清

c# - 如果没有 `typedef` ,如何创建在 C# 泛型中使用的相关类型组?

c - C语言从excel文件中读取数据

java - 最大和连续子数组(面试题)

c++ - 如何管理代码内存?

c++ - 指针类 C++

c++ - typedef 单例作为成员变量