Const correctness for array pointers?

后端 未结 3 1421
北恋
北恋 2020-11-30 09:59

Someone made an argument saying that in modern C, we should always pass arrays to functions through an array pointer, since array pointers have strong typing. Example:

3条回答
  •  星月不相逢
    2020-11-30 10:42

    C standard says that (section: §6.7.3/9):

    If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type.[...]

    Therefore, in case of const int (*arr)[n], const is applied to the elements of the array instead of array arr itself. arr is of type pointer to array[n] of const int while you are passing a parameter of type pointer to array[n] of int. Both types are incompatible.

    How do I apply const correctness to array pointers passed as parameters? Is it at all possible?

    It's not possible. There is no way to do this in standard C without using explicit cast.

    But, GCC allow this as an extension:

    In GNU C, pointers to arrays with qualifiers work similar to pointers to other qualified types. For example, a value of type int (*)[5] can be used to initialize a variable of type const int (*)[5]. These types are incompatible in ISO C because the const qualifier is formally attached to the element type of the array and not the array itself.

     extern void
     transpose (int N, int M, double out[M][N], const double in[N][M]);
     double x[3][2];
     double y[2][3];
     ...
     transpose(3, 2, y, x); 
    

    Further reading: Pointer to array with const qualifier in C & C++

提交回复
热议问题