arrayscpointersfunction-declaration

Use of const keyword with array pointers in C


In the 9th edition of Deitel's book C. How to program (chap. 7), a function is declared as

void bubbleSort(int * const array, size_t size)

and in the text it's specified that "function bubbleSort's header declares array as int * const array rather than int array[] to indicate that bubbleSort receives a one-dimensional array argument. Again, these notations are interchangeable; however, array notation generally is preferred for readability". Since "array names are constant pointers to the array's first element" (quoting from the same chapter), and since a constant pointer to a non-constant data is defined (for example) with int * const myPtr, it makes sense that array as int * const array is equivalent to the more compact array notation when dealing with arrays.

However, at the beginning of the same chapter on pointers, the authors states that "When the compiler encounters a function parameter for a one-dimensional array of the form int b[], the compiler converts the parameter to the pointer notation int *b. The two forms are interchangeable".

So, according to the authors, both int * const array and int *array are equivalent to int array[]. Why add the const keyword if they're array names, and thus by defintion constant pointers to the array's first element? Or is this not true when arrays are passed to a function?


Solution

  • So, according to the authors, both int * const array and int *array are equivalent to int array[].

    Partially.

    The position of the const matters:

    Since array names are constant pointers to the first element of the array,

    No, they are not. Arrays decay to pointers to its first element when used in expressions or as function parameters. But not const pointers

    Conclusion:

    void foo(int array[])
    void foo(int *array)
    

    do the same

    These ones:

    void foo(int array[])
    void foo(int *const array)
    

    Do not as the parameter has a different type.