Clarification on pointer to a function conversion

浪尽此生 提交于 2019-12-23 17:43:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8573763/clarification-on-pointer-to-a-function-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!