简体   繁体   English

返回数组与返回int64_t(C / C ++)

[英]Returning an array vs returning int64_t (C/C++)

Again and again I read that you can't return an array from a function (in C/C++), but if that's the case, how can an int64_t be returned from a function? 我一遍又一遍地读到您不能从函数返回数组(在C / C ++中),但是如果是这种情况,如何从函数返回int64_t Isn't int64_t just an array of long int ? int64_t不仅仅是long int的数组吗?

(Yes, I know you can return a pointer to the start of an array, but I'm talking about returning int[4] , not int* .) (是的,我知道您可以返回一个指向数组开头的指针,但是我说的是返回int[4] ,而不是int* 。)

Isn't int64_t just an array of long int? int64_t不仅仅是long int的数组吗?

No, int64_t is an alias to a scalar type (as opposed to an aggregate type like an array type), and usually it is an alias to long long type. 不, int64_t是标量类型的别名(与诸如数组类型的聚合类型相反),通常它是long long类型的别名。

Of course this applies when int64_t is defined as exact-width integer types are optional in C. 当然,当int64_t被定义为精确宽度整数类型在C中是可选的时,这适用。

You can actually return any type that isn't an array - for example, if you wish to return four int values, you can return a struct my_4ints { int x[4] }; 实际上,您可以返回不是数组的任何类型-例如,如果您希望返回四个int值,则可以返回一个struct my_4ints { int x[4] };

But int64_t (on a 32-bit machine) is one 'item'. 但是int64_t(在32位计算机上)是一个“项目”。 It happens to be returned as two register values, on x86, typically eax, edx. 它恰好在x86(通常是eax,edx)上作为两个寄存器值返回。 But that's still returning ONE value. 但这仍然返回一个值。

If you wrap your array in a struct, you can return it from a function. 如果将数组包装在结构中,则可以从函数返回它。 But it is to be avoided because the ABIs are not completely stable on these kind of thing (example: objects compiled with gcc 3.3 linked to objects compiled with gcc 3.4 on Solaris are not compatible and may crash in that case). 但这是可以避免的,因为ABI在这种情况下并不完全稳定(例如:用gcc 3.3编译的对象与Solaris上用gcc 3.4编译的对象链接不兼容,在这种情况下可能会崩溃)。

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

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