开发者

Function Returning Int Despite a Different Return Type Definition

So I'm a little confused here. I'm working 开发者_如何学运维on a bigger project, but ran into a few problems, so I wrote a little test case using a simple struct:

#include <stdio.h>

typedef struct{
    int property1;
}test;

int main(){
    test testing = getNumber();
    printf("%d",testing.property1);
    return 0;
}

test getNumber(){
    test testing = {2};
    return testing;
}

All I'm trying to do is read a property from the test struct returned from getNumber(). However, the compiler complains with the following error:

test.c(8) : error C2440: 'initializing' : cannot convert from 'int' to 'test'

So my question is: why is this function trying to return an int despite me specifying a test return type? How do I fix this? Am I just blind to something simple?


You're missing a prototype:

#include <stdio.h>

typedef struct{
    int property1;
}test;

test getNumber(void); // <<< missing prototype

int main(){
    test testing = getNumber();
    printf("%d",testing.property1);
    return 0;
}

test getNumber(void){
    test testing = {2};
    return testing;
}


The error message here is a bit ambiguous. The default return type of a c function is int. Compiler is reporting that it cannot make the conversion from int to test. But in fact, it failed because it didn't know what getNumber() is. Compiler error message should have been a bit clearer saying undefined call to getNumber() or some thing on those lines.

C compiler works on a top to bottom approach. What ever variables used, function calls made should be known to it before hand. So when compiler sees the following statement -

test testing = getNumber();

until this point it doesn't know what getNumber() is. So, you have two options making compiler happy.

  1. Either forward declare the function declaration.
  2. Or move the function definition above main().
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜