According to the code given below and the answer for it:
Question: Which of the following structure declarations will throw an error?
struct temp { char c; } s; int main(void) {}
struct temp { char c; }; struct temp s; int main(void) {}
struct temp s; struct temp { char c; }; int main(void) {}
None of the above.
Answer: 4
Is this correct? Can we declare a structure object first and only then the structure definition?
A "structure declaration" names a type and specifies a sequence of variable values (called "members" or "fields" of the structure) that can have different types. An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type.
Syntax to Define a Structure in Cdata_Type: The data type indicates the type of the data members of the structure. A structure can have data members of different data types. member_name: This is the name of the data member of the structure. Any number of data members can be defined inside a structure.
A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
Yeah, C is weird sometimes. Because that variable is at file scope and has no initializer or storage class specifier, it constitutes a tentative defintion. The C standard defines it as follows:
6.9.2 External object definitions
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
I emphasized the relevant part. Because there is no initializer on your variable, it's as though you'd written it at the very end of the file and initialized to zero. The physical layout of the file is immaterial, because logically, the definition of the structure type is available at the end of the file.
So the answer is indeed (4). I wouldn't write code like that in real life however, this is terribly confusing in the C eco-system where near everything must be pre-declared to be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With