Forward referencing with typedef

David Brown david.brown@hesbynett.no
Sat Dec 10 12:08:00 GMT 2011


(Please don't top-post - you make a mess of the flow of the 
conversation, especially for people who haven't been following it.  I've 
moved your comments below.)

On 10/12/11 05:15, Divyesh wrote:
> David Brown-4 wrote:
>>
>> On 09/12/2011 08:26, Divyesh wrote:
>>>
>>> Hi,
>>>
>>> Please refer to the following code snippet.
>>>
>>> struct strArr;
>>>
>>> typedef struct strArr myStAr[17];
>>>
>>> typedef struct
>>> {
>>> 	unsigned short DISPLAY_:1;
>>> } structDisp;
>>>
>>> typedef structDisp disp;
>>>
>>> struct strArr
>>> {
>>> 	disp dispBit;
>>> } ;
>>>
>>> int f()
>>> {
>>> 	return 0;
>>> }
>>>
>>>
>>> In the code we have a typedef to an array of struct.
>>>
>>> Now since the definition of that struct is given after the use, gcc
>>> cribs.
>>>
>>> The error reported by gcc is : array type has incomplete element type.
>>>
>>> Interesting thing is gcc 3.4.4 compiles the code where as gcc 4.3.4 and
>>> 4.6
>>> doesn't.
>>>
>>> I think this is a gcc bug.
>>>
>>> Request assistance for the same.
>>>
>>> Thanks and Regards,
>>> Divyesh
>>
>> It is not a bug.  It is interesting that gcc 3.4.4 accepted the code, as
>> it is (AFAIK) invalid C.
>>
>> It is easy to see what is going on when you think about how the compiler
>> will interpret this - starting from the top and moving down.  The usual
>> use of forward struct declarations is so that you can make pointers to
>> them in a circular type definition - that works fine, because the
>> compiler can conceive of a "pointer to struct" without knowing the
>> details of the struct.  But the compiler cannot work with an instance of
>> the forward-declared struct, or an array of them, or use it as an
>> element in another struct (only pointers are allowed) - all these things
>> require a knowledge of the size of the struct.
>>
 >
 > But it is interesting to see that g++ does compile this sample of code
 >
 > So I am confused now as there are inconsistencies between gcc and g++
 >
 >

It's easy to see that a C compiler /could/ accept the code - as long as 
the typedef you made there was never used.  I think it's just a case of 
newer gcc being stricter about not accepting bad code.

mvh.,

David



More information about the Gcc-help mailing list