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

时间:2019-11-26 18:54:05

标签: c typedef

我并不是说这是一种好的编程风格,但是我很惊讶它编译后[*]并且运行时没有任何抱怨:

map

除了可能使人感到困惑之外,C标准中是否还有任何禁止使用相同名称的类型和形式参数的东西?

[*](在本例中为Apple clang版本11.0.0(clang-1100.0.33.8)。)

1 个答案:

答案 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。这可能就是代码起作用的原因。