Why does C disallow an array return type?

前端 未结 3 732
无人共我
无人共我 2021-01-15 20:58

Why is this valid in C

int * foo(int a,int b){
...
}

but this is invalid

int [] foo(int a,int b){
...
}
3条回答
  •  感动是毒
    2021-01-15 21:37

    First, recall that arrays in C are really just syntactic sugar around pointers to blocks of memory. So C isn't restricting the functionality of the language by forcing the use of the former notation (See the example which follows).

    Also, they may have made this choice to prevent early programmers from writing code like this:

    char *itoa(int n){
        char retbuf[25];
        sprintf(retbuf, "%d", n);
        return retbuf;
    }
    

    ref

    Which looks simple enough, but what happens to the memory retbuf points to at the end of the function? Can the calling functions trust the data in the pointer it gets back?

提交回复
热议问题