简体   繁体   English

定义函数的奇怪类型

[英]A weird type of defining a function

I learning C for 1 years, i saw a type of defining a function. 我学习了C 1年,我看到了一种定义函数的方法。 I couldn't name it, so i want to know the name of the defining function. 我无法命名,所以我想知道定义函数的名称。

We defining functions as standard: 我们将功能定义为标准:

FunctionReturnType FunctionName(FunctionArgs)
{
  codes();
}

But i saw that type: 但是我看到了那种类型:

FunctionReturnType FunctionName(FunctionArgs)(TheWeirdArea)
{
  codes();
}

So what we doing for in i named as TheWeirdArea? 那么我们在做什么名为TheWeirdArea? I guess it's relative with function arguments, but i want to know correctly what we do in TheWeirdArea. 我猜它与函数参数有关,但我想知道我们在TheWeirdArea中做了什么。

I guess this is about returning a function pointer to a function looking like 我想这是关于返回一个看起来像函数的函数指针

FunctionReturnType func(TheWeirdArea);

Here is an example: 这是一个例子:

#include <stdio.h>

int bar1(int b)
{
    printf("bar1\n");
    return 42 + b;
}

int bar2(int b)
{
    printf("bar2\n");
    return 100 + b;
}

int (*foo(int a))(int b)  // Returns a function pointer
{
    if (a == 1) return bar1;
    return bar2;
}

int main(void) {
    printf("%d\n", foo(1)(100));
    printf("%d\n", foo(2)(200));
    return 0;
}

Output: 输出:

bar1
142
bar2
300

Hope this dummy example help you 希望这个虚拟的例子能帮到你

int add(int x,int y)
{
return x+y;   //very dummy function return x+y
}


typedef int (*pointer_to_add)(int,int);
/* this is a declaration of  function pointer works 

with any function has an int return type and

 accept two int arguments not only add */

int (*my_function(int arg1, double arg2))(int, int)
{
   /*This a function accept an int argument 

arg1 and double arg2 and return pointer to a function or address of function

which has a two int type arguments and return an int */

pointer_to_add  ptr=add; //ptr is a pointer now to add function.

return  ptr;
} 

More simple form 更简单的形式

pointer_to_add my_function(int arg1,double arg2)
{

 pointer_to_add ptr=add;

 return ptr;

 }

Now in your main code you can use the returned address like: 现在在主代码中,您可以使用返回的地址,如:

 int main(void)
  {
    pointer_to_add P=my_function(25,3.5);
    printf("%i",p(22,33));
    return 0;
    } 

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

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