为什么在 C++ 中函数的任何索引处的下标运算符总是 returns 1?

Why does the subscript operator at any index on a function always returns 1 in C++?

这是我的代码。似乎 f[i] returns 1 在 i.

的任何值
int f(int x) { return 203; }

int main(){
  cout<<f[0]<<' '<<f[21]<<' 'f[-1];//= 1 1 1
  return 0;
}

根据编译器抛出的警告,我知道这是一个指针,但它的行为似乎不像一个指针。

f[-2](1) // = 203, good
f[32](1) // Process returned -1073741571 (0xC00000FD)   execution time : 6.731 s

编辑:我使用带有 c++ 14 标志的 g++ 编译器。

它是一个 GCC 扩展:

6.23 Arithmetic on void- and Function-Pointers

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

如果调用指向不存在函数的指针,很可能会崩溃或产生奇怪的结果。


It seems that f[i] returns 1 at any value of i.

这是 cout 的众所周知的行为。它将所有非零函数指针打印为 1,因为它们没有适当的 operator<< 重载,并且 operator<<(bool) 被选为最合适的重载。

f[i] 是函数而不是函数指针,但在这种情况下它会衰减为指针。)