简体   繁体   English

结构返回功能

[英]Structure returning function

In C component selection, what is the benefit of structure-returning function? C组件选择中,结构返回功能有什么好处? for example: 例如:

struct S {
   int a, b;
} x;

Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this? 为什么我可以将上面的结构分配为如下所示的函数,这样做有什么好处?

extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accurate */

Open my eyes on this guys. 睁开眼睛看着这些家伙。

It's just a function that happens to return a struct . 它只是一个返回struct There's nothing more to it than that. 没有什么比这更重要了。 You wouldn't be surprised to see a function return an int , why be surprised when one returns a struct? 看到一个函数返回一个int你会不会感到惊讶,当一个返回一个结构时为什么会感到惊讶?

As an aside, the extern is superfluous here because that is the default storage class for functions. 另外, extern在这里是多余的,因为这是函数的默认存储类。

It is useful so that you can return multiple values from a function. 它非常有用,您可以从函数中返回多个值。

For example, you can use it like this 例如,您可以像这样使用它

struct Point {
   int x;
   int y;
};

struct Point getMousePos()
{
    struct Point pos;
    pos.x = 567;
    pos.y = 343;
    return pos; 
}

int main()
{
    struct Point mouse_pos = getMousePos();
    printf("Mousepos %d,%d\n", mouse_pos.x, mouse_pos.y");   
}

The function can be forward declared with extern (this would normally be done in a header file), so that other functions know its prototype ie its parameters and return type, even if the function is itself defined in another file. 该函数可以使用extern进行前向声明(这通常在头文件中完成),以便其他函数知道其原型,即其参数和返回类型,即使该函数本身在另一个文件中定义。

如果你得到一个结构的副本而不是指向它的指针,你知道你永远不必担心free()它,或者是否有任何数据争用,其中一个线程正在写入结构而另一个线程从中读取,或者该函数返回的指针是否会被某些可能超出您控制范围的操作无效。

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

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