调用函数指针时,星号是可选的吗? [英] Is the asterisk optional when calling a function pointer?

查看:217
本文介绍了调用函数指针时,星号是可选的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何地方都找不到答案.我刚刚读过K& R,看到他们像这样调用函数指针:

I couldn't find an answer to this anywhere. I just read K&R and saw them calling a function pointer like this:

(*ptr)(arg1, arg2);

但是,我生动地记得曾经见过有人像这样使用它们:

I vividly remember, however, to have seen someone using them like this:

ptr(arg1, arg2);

不过可能是C ++.

  • 规则如何?
  • 它们在C和C ++中有区别吗?

推荐答案

TL; DR

C和C ++中的规则相同,两者没有区别.

C ++标准是什么( n3797 )说?

What does the C++ Standard (n3797) say?

5.2.2p1 函数调用 [expr.call]

函数调用是后缀表达式,后跟括号 包含一个可能的,用逗号分隔的空列表 构成该函数参数的初始化子句.

A function call is a postfix expression followed by parentheses containing a possible empty, comma-separated list of initializer-clauses which constitute the arguments to the function.

后缀表达式应具有函数类型或指向函数类型的指针.


C标准是什么( n1570 )说?


What does the C standard (n1570) say?

6.3.2.1p4 左值,数组和函数指示符

函数指示符是具有函数类型的表达式.除非它是sizeof运算符,_Alignof运算符或一元&运算符的操作数,否则类型为函数返回 type "的函数指示符将被转换为表达式的类型为指向返回 type 类型的函数的指针" .

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".

6.5.2.2p1 函数调用

表示被调用函数的表达式应具有指向该函数的类型指针,返回void或返回除数组类型以外的完整对象类型.

The expression that denotes the called function shall have type pointer to function returning void or returning a complete object type other than an array type.



结论?



Conclusion?

规则的表达方式在C ++和C之间有所不同.在C中,隐式函数到指针转换在调用函数时始终适用,而C ++指出后缀表达式" 可以是指针,也可以是函数类型的变量.

How the rule are expressed differs between C++ and C. In C the implicit function-to-pointer conversion always applies when calling a function, whereas C++ states that the "postfix expression" could be either a pointer, or a variable of function type.

但是;您的问题是,通过指针调用函数的两种方式在C ++和C之间是否不同,并且答案是:否,(1)(2)(3)之间没有区别 ,这两种语言之间也没有区别.

However; your question is if the two ways of calling a function through a pointer differs between C++ and C, and the answer is: No, there's no difference between (1), (2), and (3), nor is there a difference between the two languages.

(*fptr)(123);   // (1)

fptr(123);      // (2)

(***fptr)(123); // (3)


注意:请注意,在调用函数时,(*fptr) (...)fptr (...)之间没有什么区别,但是在其他情况下它们可以有很大的不同.


Note: Be aware that the there's no difference between (*fptr) (...) and fptr (...) when it comes to calling a function, but that they can be vastly different in other contexts.

这篇关于调用函数指针时,星号是可选的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆