简体   繁体   English

指向函数及其返回类型(无效)的指针

[英]Pointer to a function and its return type (void)

Is such declaration void *(*function) () is valid ? 这样的声明void *(*function) ()是否有效? If it is valid then *function will return any address to called function . 如果有效,则*function将把任何地址返回给被调用的function。 At that address, what value is returning? 在那个地址,返回什么值? Is value save at that address is 0. If it is zero,what is the difference between return 0 and return nothing in function having return type void . 在该地址保存的值是否为0。如果为零,则在返回类型为void函数中,返回return 0和什么都不返回之间的区别是什么。

The notation 记号

void * (*function)();

means “declare a function pointer named function , which points to a function that takes an unspecified number of arguments, then returns a void * .” 意思是“声明一个名为function的函数指针,该指针指向一个函数,该函数接受未指定数量的参数,然后返回void * 。”

Since this just declares a variable, it doesn't define a function and so nothing can be said about what value is going to be returned. 由于这仅声明了变量,因此未定义函数,因此对于要返回的值什么也没说。 You'd need to assign this pointer to point to a function before you can call it. 您需要先分配此指针以指向一个函数,然后才能调用它。

Once you do assign function to point to something, if you call function , you'll get back a void * , which you can think of as “a pure memory address” since it contains an address but can't be dereferenced to an object without a cast. 一旦分配了function以指向某个对象,如果调用function ,您将获得一个void * ,您可以将其视为“纯内存地址”,因为它包含一个地址,但无法取消引用到对象没有演员。

Notice that returning a void * is not the same as as a function that has a void return type. 请注意,返回void *与具有void返回类型的函数不同。 The former means “I return a memory address,” and the latter means “I don't return anything at all.” 前者的意思是“我返回一个内存地址”,而后者的意思是“我什么都不返回”。

The declaration is read as follows: 该声明的内容如下:

        function        -- function is a 
       *function        -- pointer to 
      (*function) ()    -- function taking unspecified parameters
     *(*function) ()    -- returning pointer to
void *(*function) ();   -- void

So, function is a pointer to a function type, not a function itself. 因此, function指向函数类型的指针 ,而不是函数本身。 You could have multiple functions, each returning pointers to void : 您可能有多个函数,每个函数都返回指向void指针:

void *foo( void )    { ... }
void *bar( void )    { ... }
void *bletch( void ) { ... }

You can use the function pointer to point to each of those functions, and decide at runtime which to call: 您可以使用function指针指向每个这些函数,并在运行时确定要调用的函数:

if ( condition1 )
  function = foo;
else if ( condition2 )
  function = bar;
else
  function = bletch;

void *ptr = function(); // or (*function)();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM