关于函数指针转换的澄清

发布于 2024-12-22 05:19:58 字数 242 浏览 2 评论 0原文

函数类型(左值)可以转换为函数指针(右值)。

int func();
int (*func_ptr)() = func;

但从 (4.1/1)

可以转换非函数、非数组类型 T 的左值 (3.10) 为右值。

这是否意味着函数上未完成左值到右值的转换?另外,当数组衰减为指针时,它不会返回一个作为指针的右值吗?

A function type (lvalue) can be converted to a pointer to function (rvalue).

int func();
int (*func_ptr)() = func;

But from (4.1/1)

An lvalue (3.10) of a non-function, non-array type T can be converted
to an rvalue.

Does it mean that a lvalue to rvalue conversion is not done on functions? Also, when an array decays to pointer doesn't it return a rvalue which is a pointer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妄断弥空 2024-12-29 05:19:58

函数是左值。指向函数(数据类型)的指针可以是
任何一个;如果你给它一个名字,它就是一个左值;否则,它不是
(粗略地说)。指向函数的指针遵循所有常见的左值
到右值转换规则。对于简单类型,例如基本类型或
指针,左值到右值的转换基本上意味着读取
多变的。

void func();            //  Declares func
(*(&func))();           //  The expression &func is an rvalue
void (*pf)() = &func;   //  pf is an lvalue
(*pf)();                //  In the expression *pf, pf undergoes an
                        //  lvalue to rvalue conversion

请注意,存在函数到指针的隐式转换
函数,并且 () 运算符适用于函数和
指向函数的指针,因此最后两行可以这样写:

void (*pf)() = func;
pf();

与往常一样,转换的结果是一个右值(除非
转换为引用类型)。当数组
隐式转换为指针;数组和函数都只能
作为左值存在,但是它们都隐式转换为指针,
这是一个右值。但该指针可用于初始化
适当指针类型的变量;这些变量是左值。

Functions are lvalues. A pointer to a function (a data type) can be
either; if you give it a name, it's an lvalue; otherwise, it's not
(roughly speaking). Pointers to functions obey all of the usual lvalue
to rvalue conversion rules. For simple types like the basic types or
pointers, the lvalue to rvalue conversion basically means reading the
variable.

void func();            //  Declares func
(*(&func))();           //  The expression &func is an rvalue
void (*pf)() = &func;   //  pf is an lvalue
(*pf)();                //  In the expression *pf, pf undergoes an
                        //  lvalue to rvalue conversion

Note that there is an implicit conversion of function to pointer to
function, and that the () operator works on both functions and
pointers to functions, so the last two lines could be written:

void (*pf)() = func;
pf();

As always, the result of the conversion is an rvalue (unless the
conversion is to a reference type). This is also the case when an array
is implicitly converted to a pointer; both arrays and functions can only
exist as lvalues, but they both implicitly convert to a pointer,
which is an rvalue. But that pointer can be used to initialize a
variable of the appropriate pointer type; such variables are lvalues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文