I'm having an issue trying to nest structs that I need to declare as new var types. The code is the following-
typedef struct
{
typedef struct
{
int day,
month,
year;
} Date;
Date manuDate,
purDate;
double purPrice;
} Car;
Except when I try to compile it throws an error at me saying
"Syntax error before typedef" and a bunch of other errors due to that further down.
Is this something C cannot do? I know it has issues with nested structs without having a pointer but I'm not sure how that would work in this case...
typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.
A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.
C does not support nested structure definitions. Perhaps you were looking at some C++ code.
Instead, you simply define the "inner" struct first, and then reference it within the "outer" struct.
typedef struct
{
int day,
month,
year;
} Date;
typedef struct
{
Date manuDate,
purDate;
double purPrice;
} Car;
C does have nested structs/unions/enums but not nested typedefs.
struct A { typedef struct B { int x; } B; }; //WRONG
struct A { struct { int x; } b; }; //OK - an anonymous nested struct w/ an instance
struct A { struct { int x; }; }; //OK - an anonymous nested struct w/out an instance; x effectively belongs to `struct A`
struct A { struct B { int x; } b; }; //OK, the `struct B` type also becomes available in the outer scope
struct A { struct B { int x; }; }; //WRONG, an tagged nested struct needs at least 1 instance
The nested structs/unions/enums can either be anonymous (untagged) in which case they become part of the outer struct/union or tagged.
An anonymous inner struct/union can also get away without defining instances, in which case the inner members become members of the outer struct/union recursively.
A tagged nested struct/union/enum needs instances and it's like an anonymous nested struct/union/enum with instances except the tagged type also becomes available for later use, behaving as if it were a standalone outer-scope struct/union/enum definition.
It might be wise to simply put a tagged struct/union/enum in the outer scope rather than confusingly nest it inside another struct/union.
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