Strange warning in a C function const multidimensional-array argument

前端 未结 6 1882
长发绾君心
长发绾君心 2020-11-29 11:43

I\'m getting some strange warnings about this code:

typedef double mat4[4][4];

void mprod4(mat4 r, const mat4 a, const mat4 b)
{
/* yes, function is empty *         


        
6条回答
  •  生来不讨喜
    2020-11-29 12:10

    To explain what Joseph said: the function is expecting a pointer to array[4] of const double to be passed in, but you're passing in a pointer to array[4] of double. These types are not compatible, so you get an error. They look like they should be compatible, but they're not.

    For the purposes of passing parameters to functions (or for variable assignments), you can always convert an X to a const X, or a pointer to X to a pointer to const X for any type X. For example:

    int x1 = 0;
    const int x2 = x1;  // ok
    int *x3 = &x1;
    const int *x4 = x3;  // ok: convert "pointer to int" to "pointer to const int"
    int **x5 = &x3;
    const int **x6 = x5;  // ERROR: see DigitalRoss's answer
    int *const *x7 = x5;  // ok: convert "pointer to (pointer to int)" to
                          //             "pointer to const (pointer to int)"
    

    You're only allowed to add qualifiers (that is, the const, volatile, and restrict qualifiers) to the first level of pointers. You can't add them to higher levels of pointers because, as DigitalRoss mentioned, doing so would allow you to accidentally violate const-correctness. This is what Joseph means by "the only case where qualifiers are permitted to be added in assignment, argument passing etc. is qualifiers on the immediate pointer target, not those nested more deeply."

    So, bringing us back to Joseph's response, you can't convert a pointer to array[4] of double to a pointer to array[4] of const double because there is no type X such that you're converting from pointer to X to pointer to const X.

    If you try using array[4] of double for X, you'd see that you can convert to pointer to const array[4] of double, which is a different type. However, no such type exists in C: you can have an array of a const type, but there is no such thing as a const array.

    Hence, there's no way to perfectly solve your problem. You'll have to either add casts to all of your function calls (either manually or via a macro or helper function), rewrite your functions to not take const parameters (bad since it doesn't let you pass in const matrices), or change the mat4 type to be either a 1-dimensional array or a structure, as user502515 suggested.

提交回复
热议问题