c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?

标签 c++ syntax function-pointers

有趣的是,将函数名用作函数指针等同于将寻址运算符应用于函数名!

这是例子。

typedef bool (*FunType)(int);
bool f(int);
int main() {
  FunType a = f;
  FunType b = &a; // Sure, here's an error.
  FunType c = &f; // This is not an error, though. 
                  // It's equivalent to the statement without "&".
                  // So we have c equals a.
  return 0;
}

使用名称是我们在数组中已经知道的。但是你不能写类似

的东西
int a[2];
int * b = &a; // Error!

这似乎与语言的其他部分不一致。这样设计的原理是什么?

This question explains the semantics of such behavior and why it works.但我对为什么要这样设计语言很感兴趣。

更有趣的是函数类型在用作参数时可以隐式转换为指向自身的指针,但在用作返回类型时不会转换为指向自身的指针!

示例:

typedef bool FunctionType(int);
void g(FunctionType); // Implicitly converted to void g(FunctionType *).
FunctionType h(); // Error!
FunctionType * j(); // Return a function pointer to a function 
                    // that has the type of bool(int).

最佳答案

由于您特别询问此行为的基本原理,这是我能找到的最接近的东西(来自 ANSI C90 基本原理文档 - http://www.lysator.liu.se/c/rat/c3.html#3-3-2-2):

3.3.2.2 Function calls

Pointers to functions may be used either as (*pf)() or as pf(). The latter construct, not sanctioned in the Base Document, appears in some present versions of C, is unambiguous, invalidates no old code, and can be an important shorthand. The shorthand is useful for packages that present only one external name, which designates a structure full of pointers to object s and functions : member functions can be called as graphics.open(file) instead of (*graphics.open)(file). The treatment of function designators can lead to some curious , but valid , syntactic forms . Given the declarations :

int f ( ) , ( *pf ) ( ) ; 

then all of the following expressions are valid function calls :

( &f)(); f(); (*f)(); (**f)(); (***f)();
pf(); (*pf)(); (**pf)(); (***pf)();

The first expression on each line was discussed in the previous paragraph . The second is conventional usage . All subsequent expressions take advantage of the implicit conversion of a function designator to a pointer value , in nearly all expression contexts . The Committee saw no real harm in allowing these forms ; outlawing forms like (*f)(), while still permitting *a (for int a[]), simply seemed more trouble than it was worth .

基本上,添加了函数指示符和函数指针之间的等价性,使函数指针的使用更加方便。

关于c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319977/

相关文章:

c++ - vc++ 不再使用基于范围的语法对简单的 for 循环进行矢量化

c++ - 我如何转发声明句柄? (Win32)

arrays - 如何在swift中初始化一个命名元组数组

c - 函数指针相对于标志的优势

javascript - 自修改功能不好吗?

c++ - 推导函数指针返回类型

c++ - Qt5 OpenGL GLSL 版本错误

c++ - Windows 风格的 getopt/argp

python - python字典中的函数

c - 在定义整数常量表达式时间接禁止(或不禁止?)运算符(在 C 中)