Search code examples
carraysfunction-call

Variable declaration in function prototype and in block code : difference?


Why int array[] raise a compilation error in main but not in function prototype ? Should it mean that it is better to always write int * array in function prototype ?

void myfoo (int array[]) { // No compilation error
;}

void myfoo1 (int *array1) { // No compilation error
;}

int main() {
    int array[]; // Compilation error
    int* array1; // No compilation error
}

Solution

  • Fundamentally, the reason an array declaration inside the block for main needs a size and the array declaration in the function parameter does not is that the declaration in main is defining an array, whereas the function parameter is merely receiving an array that something else defines.

    So the definition in main needs a size because it must reserve storage for the array.

    The function parameter is merely receiving an array, so it only needs to know where the array starts. It does not need to know the size. (That is, the compiler does not need to know the size in order to compile the code. The function may need to know the size in order to perform its intended purpose, but that is a matter for the programmer, not the compiler.)

    Due to C rules, arrays can never actually be passed as function arguments. Whenever an array is given as a function parameter, the compiler automatically converts it to a pointer to its first element. Similarly, a function parameter can be a pointer but cannot actually be an array. When you declare a function parameter as an array, the compiler automatically adjust it to declare a pointer instead. So the function declaration void myfoo(int array[]) is automatically adjusted to be void myfoo(int *array).

    The specific rule that requires the declaration in main to have a size is C 2018 6.7 7:

    If an identifier for an object is declared with no linkage, the type for the object shall be complete by the end of its declarator, or by the end of its init-declarator if it has an initializer;…