具有非默认类型的函数的返回值

时间:2012-01-05 15:56:10

标签: c function return-value return-type

我有一个功能:

*Foo* create_foo();

其中Foo是一个包含许多字段的结构:

typedef struct foo {
    int progr_num;
    char* size;
    char* account;
    int matric_num;
    int codex_grp;
    char* note;
} Foo;

当我调用它时,该函数的确切返回值是什么?

功能:

Foo create_foo() {
    Foo x;
    ...
    ...
    return x
}

我知道返回类型是Foo,但如果我调用该函数并想测试返回值,这是正确的值? (例如,如果函数是 int 类型,则返回值为0或-1)。

当我调用函数时返回正确值是什么?

例如:

int main() {
    Foo foo_check;
    foo_check = create_foo();
    if(!foo_check)
    return ... **???**
}

4 个答案:

答案 0 :(得分:1)

不是在堆栈上来回传递(大)结构,而是传递指针并使用堆栈作为状态指示器。

struct foo { /* ... whatever ... */ };
int fxfoo(struct foo *pfoo) { /* ... whatever ... */ return ALLOK?0:1; }
int main(void) {
    struct foo objfoo;
    if (fxfoo(&objfoo)) /* error */;
}

答案 1 :(得分:0)

返回值是结构Foo的完整实例。如果您想检查其值,则必须将其分配给某个内容,然后逐字段检查。

答案 2 :(得分:0)

struct A{
int x;
char c;
}

Foo create_foo(){
struct A a;
a.x = 5;
a.c = 'd';

return a; // <-- This will be your return value.
}

答案 3 :(得分:0)

您使用返回值的方式与使用任何返回值的方式相同......

Foo x = create_foo();
if(x.field == y) {...};