Multidimentional arrays generate an unexpected error
Since the commit https://github.com/llvm/llvm-project/commit/b24769855d97697de08e2296a548c033f193caf4 and associated pull request https://github.com/llvm/llvm-project/pull/157364 the following code:
#include <stdio.h>
int afunc(unsigned long * v)
{
return v != NULL;
}
unsigned long mdarr[5][6];
unsigned long sdarr[30];
int main()
{
afunc(sdarr);
afunc(mdarr);
printf("mdarr = %zu \n", sizeof(mdarr));
printf("sdarr = %zu \n", sizeof(sdarr));
return 0;
}
generate an error:
error: incompatible pointer types passing 'unsigned long[5][6]' to parameter of type 'unsigned long *' [-Wincompatible-pointer-types].
Please see godbolt example.
However the ISO/IEC 9899:1999 standard in 6.5.2.1 Array subscripting says:
If E is an n-dimensional array (n ≥ 2) with dimensions i × j × . . . × k, then E (used as other than an lvalue) is converted to a pointer to an (n − 1)-dimensional array with dimensions j × . . . × k. If the unary * operator is applied to this pointer explicitly, or implicitly as a result of subscripting, the result is the pointed-to (n − 1)-dimensional array, which itself is converted into a pointer if used as other than an lvalue.
effectively requiring compatibility between multidimensional array and pointer. Thus it looks like a diagnostics should not be generated in such case as standard compliant compiler should guarantee compatibility between all 3 types unsigned long *, unsigned long [5][6], unsigned long [30] .
GCC diagnoses this too so I’m not sure this is right candidly. I’m also not an expert on the C standard though (and the person who I’d normally ask about this is currently on a sabbatical)
GCC diagnoses this too
Looks like pretty much every C compiler on godbolt diagnoses this actually.
However the ISO/IEC 9899:1999 standard in 6.5.2.1 Array subscripting says:
If E is an n-dimensional array (n ≥ 2) with dimensions i × j × . . . × k, then E (used as other than an lvalue) is converted to a pointer to an (n − 1)-dimensional array with dimensions j × . . . × k. If the unary * operator is applied to this pointer explicitly, or implicitly as a result of subscripting, the result is the pointed-to (n − 1)-dimensional array, which itself is converted into a pointer if used as other than an lvalue.effectively requiring compatibility between multidimensional array and pointer. Thus it looks like a diagnostics should not be generated in such case as standard compliant compiler should guarantee compatibility between all 3 types
unsigned long *,unsigned long [5][6],unsigned long [30].
Also, that section in particular is about subscripting; the sentence before the part you quoted is
Successive subscript operators designate an element of a multidimensional array object
so this doesn’t seem like it would apply here given that no subscripting is taking place in the call to afunc(mdarr).
I do not think one needs to be an expert here as we have a standard an it is the one and single source of truth. And my reading tells me that while the whole paragraph indeed talks about subscripting of multidimentional array it (please follow my inferences):
- Does establish equivalence
unary * operator is applied to this pointer explicitly, or implicitly as a result of subscriptingbetween results of the the subscripting. - Thus we have an object, which when applied 2 different operations
*and subscripting that is required to produce identical results for the elements access. - Pointer is following the same semantics to provide access to it's element as required equivalency stated in the same paragraph.
- Thus pointers are indeed compatible for the elements access purposes.
- There is no standard requirement (or at least i have not found it) to have those pointers to be incompatible for any other purposes or declared as an UB.
- From my godbolt experiments i concluded in all compilers the explicit cast produces the compatible pointer for ALL valid purposes. Other purposes i checked are address arithmetic and comparisons.
- The warning currently claims pointer incompatibility which is not correct from both piratical and standard induced (for element access) point-of-views.
- Thus the warning or moreover the error as is it is spelled now is incorrect and confusing to the developer and should be addressed as it warns about incompatibility, which is not actually here.
PS: At the end of the day as Hu Fuming stated: "Practice is the Sole Criterion for Testing Truth" (C)
So regarding this and what you said on the pr, I agree that it would intuitively make sense to allow this, but I still can’t find any place in the C standard that explicitly allow this (unless I missed a section somewhere, which is possible because I at least generally find it hard to find anything in the C standard); I don’t think it’s valid to make any such inference from how subscripting or dereferencing work (and if it’s supposed to be, I’d say the C standard needs to be revised because it’s entirely unclear to me how that would be a valid conclusion).
(Side note: I do see several mentions that this conversion applies if the array is ‘used as other than an lvalue’, but I have no idea what that’s supposed to mean, because I don’t think it’s possible to turn an array declaration into an rvalue of array type.)
You also mention that just because one or more compilers implement something a certain way doesn’t mean that they’re correct, and I agree with that, but at the same time I also find it unlikely that every C compiler got this wrong—though of course it’s not impossible. But at least in my experience, when all compilers (that I can find at least) diagnose something that I think is valid, that’s usually a sign that I’m missing something.
CC @cor3ntin @erichkeane @shafik for thoughts.
I believe the C FAQ backs up how this currently implemented My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. in particular:
... by which arrays decay into pointers is not applied recursively. ...
@shafik, thank you very much for the link. The statement in the FAQ is definitely correct and I'm fully backing it up. Applying array decay recursively does NOT makes sense because otherwise following this logic for int a[2][3][4] we need to establish equivalence with int *** type which makes zero sense.
If you will look into proposed PR it makes compiler not throwing error between int a[2][3][4] and int * as int * represents the same "flattened" (using FAQ term) array with it's shape lost inside implicit conversion.
So I'm not proposing to use array decay recursively (and never was), but instead I'm challenging the decision of throwing out error when developer implicitly "flatten" the array. Please note, now this error is enabled by default, which, by all means establish some level of severity standard.
My point is the conversion is actually compatible as we are not hitting undefined behavior or something serious, the conversion loosing the shape of array and this is it. Such conversion does NOT introduce any incompatibility.
May be it would be wise not ignore it completely like in my PR, but introduce a warning (not an error!) about implicit array "flattening". What do you think about such approach?
@Sirraide loosening this restriction in case multidimensional array on the left side makes zero sense and my change does not cover this case. I also agree in your broader statement about all compilers, however please note that "diagnose something" is not equal to "throw an error about pointer incompatibility". For example msvc says: "warning C4024: 'afunc': different types for formal and actual parameter 1" which is correct because types are indeed different. My point is throwing an error in such case is not correct and overreacting. May be some diagnostics is due in such case as shape of array is lost and user should be warned about it.
I think this is inventing language features on the fly.
The standard says (lvalue conversion)
Except when it is the operand of the sizeof operator, or the _Countof operator, or typeof operators, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is implementation-defined.
This cannot be interpreted as "convert array of array of type to pointer to type"
What we might want to consider (if this is really an issue for folks) is to put that case under a different warning flags (-Wincompatible-array-pointer-types for example) that can be disabled independently.
Not warning at all on such conversion would require either
- a small RFC
- a WG14 paper (we might want to wait for @AaronBallman to come back to weight on the pertinence of such paper)
Note that these specific conversion rules are the same in C++.
@cor3ntin the language features invitation was not an original idea, especially on the fly. My main trail of thoughts and motivation is presented in: https://github.com/llvm/llvm-project/issues/159603#issuecomment-3315998312. The main factor to create the issue was, as you notices correctly, the warning that become error and caused code breakage. My analysis showed that the code triggering the error looks "harmless" and subsequent standard analysis did not revealed anything in the standard explicitly making this situation invalid. Moreover I found sentences quoted above which moved my option to the different direction.
Summarizing the above I propose:
- Make this situation a special case, which is a warning by default (not an error). This is my motivation.
- Cover it under
Wincompatible-ndimensional-array-pointer-castto enable andWno-incompatible-ndimensional-array-pointer-castto disable. This will be automatic, but worth mentioning - Use text
incompatible implicit multidimensional array passing 'unsigned long[5][6]' to parameter of type 'unsigned long *' [-Wincompatible-ndimensional-array-pointer-cast]. - Cover 2 situations: Assignment and function parameter passing.
As for the complete removal of the warning, while from the practical standpoint I still believe it might be beneficial I do not want to pursue this route myself as it is going above and beyond my initial goals and problems I encountered in our code base. If the plan above will be accepted I'll have Wno-incompatible-ndimensional-array-pointer-cast passed to the compiler and have the issue resolved.
PS: I have no strong position regarding the exact warning wording and the parameter name as soon it is making sense.
I'm not sure I share your reading of the standard there, but would like to wait for @AaronBallman to return next week. Since other compiler's don't do it, it seems like this is a novel reading of the rule, so this perhaps requires a WG14 discussion/confirmation.
As far as allowing it as an extension: I don't believe this qualifies. We typically save extensions like this for different situations, and I'm always against extensions that relax the type system.
@erichkeane Standard does not go into much details about multidimentional arrays anyway, so it's up to the community consensus how some statements can be interpreted as soon as there different interpretations.
My main concern is the motivation for the https://github.com/llvm/llvm-project/pull/157364: https://github.com/llvm/llvm-project/issues/74605#issuecomment-1843231793 does not correspond the result achieved in this particular situation.
In particular risks for converting int * to double * are clear, but risks for converting unsigned long [5][6] to unsigned long * (besides array shape loss) are not that obvious to me especially comparing with conversion of unsigned long [30] to unsigned long * which is explicitly required by the standard.
@erichkeane Standard does not go into much details about multidimentional arrays anyway, so it's up to the community consensus how some statements can be interpreted as soon as there different interpretations. My main concern is the motivation for the #157364: #74605 (comment) does not correspond the result achieved in this particular situation. In particular risks for converting
int *todouble *are clear, but risks for convertingunsigned long [5][6]tounsigned long *(besides array shape loss) are not that obvious to me especially comparing with conversion ofunsigned long [30]tounsigned long *which is explicitly required by the standard.
Sounds like a good argument to put in the 'justification' section of your paper for WG14.
I think that accessing multi-dimensional array as a flat array is not something C and C++ wording has ever supported or intend to support (I wasn't able to find any relevant CWG issues). If such a paper arrives at either committee, I'd ask the author to gather feedback from backend folks, as this would be a change to the object model which might have implications for them.
I've seen some members of WG14 considering to deprecate array-to-pointer decay of function parameter types. So much activity in this area!
@Endilll if they did not intended it, they should have explicitly prohibit it in 6.5.2.1 Array subscripting rather then require equivalence between array and subscript for element access. But I believe discussion about intent is a moot discussion as only what is currently written in the active standard does matter.
I doubt the deprecation of array-to-pointer decay will be possible without a standard change.
@Endilll if they did not intended it, they should have explicitly prohibit it in
6.5.2.1 Array subscriptingrather then require equivalence between array and subscript for element access. But I believe discussion about intent is a moot discussion as only what is currently written in the active standard does matter. I doubt the deprecation of array-to-pointer decay will be possible without a standard change.
The point he is making, is WG14 is ACTIVELY discussing such a standards change (where actively is: on reflectors/over a few meetings).
if they did not intended it, they should have explicitly prohibit it in 6.5.2.1 Array subscripting
Both standards first and foremost describe behavior of well-formed programs, in part because the set of ill-formed programs to explicitly prohibit is infinite. One can say this is another spin on "undefined behavior by omission" approach, which is explicitly endorsed by C wording (4.2 Confromance). So you shouldn't draw conclusions from the lack of such prohibition.
So you shouldn't draw conclusions from the lack of such prohibition.
@Endilll Exactly. Lack of specific wording means unknown. If something is not prohibited we cannot say it's use is discouraged. That is why specifically I'm trying to be accurate with my wording and not to make any statements not backed up by the specific wordings in the standard or practical testing results. But in situation when i do have element access equivalence it is direct pointer, that might be compatibility in other areas is desirable as well. In such situations I like to use a duck test: If some unknown object possess some features of another known object, than those two object might be equivalent. Sometimes this test fails (like with duck imitator of quality), but it is a ground for further clarification and checking.
Anyways as proposed above, let's wait for @AaronBallman and see his position upon demotion of this error back to warning in this specific situation.
@AaronBallman Please treat this message as a gentle ping of you being summoned here.
Thank you for the ping!
Given:
int afunc(unsigned long * v);
unsigned long mdarr[5][6];
int main() {
afunc(mdarr); // #1
}
My reading of the standard is that the primary expression mdarr at #1 will decay into a pointer per 6.3.2.1. That converts from unsigned long[5][6] to "pointer to type" which points to the initial element of the array object. "Type" in this case is unsigned long[6] (6.7.7.3), so that would form the type unsigned long (*)[6] which is a pointer to an array object. A pointer to array object is not compatible with a pointer object per the type compatibility rules (6.2.7, 6.7.7.3) and so it's an invalid assignment that violates a constraint (6.5.3.3).
So I think this is all behaving according to spec and changing that would require a paper for WG14. I'm not certain what the committee's appetite for change would be here. One the way to "solve" this would be to change the type compatibility rules so that a pointer to an array of type T and a pointer to type T are compatible. That would then mean this code is accepted as well: https://godbolt.org/z/7sEYan4fT Whether that's a good language design or not is up for debate.
@AaronBallman Thank you for your opinion. Looking from point of type compatibility rules pointers are indeed different, however from the practical standpoint those pointers are the same and compatible my current question should we warn about it or should we produce an error given that noting wrong comes out of automatic typecast in line 8 of your godbolt example? My understanding is we are giving warning warning in situation like: https://godbolt.org/z/r48qha9We (see line 6) where underlying types are indeed different and giving error in situation where in all of it's practicality nothing wrong is happening. After reading your arguments i agree that some sort of diagnostics is desirable here based on clauses you sited, but now my point is why we want it to be an error and not warning like it was before? I'm totally OK to make my fix produce a warning in this situation. So my current desire is to have the error reclassified back to warning in situations like these. What is your opinion on this?