What is it called in C when you can use the same struct with functions expecting…
- User
What is it called in C when you can use the same struct with functions expecting different structs but with the same starting fields?
- Assistant
This concept is called "struct compatibility" in C. It allows you to use a struct with functions expecting different structs but with the same starting fields.
When two structs have the same starting fields in the same order, the compiler treats them as compatible. This means you can assign a pointer to one struct to the other, pass them as arguments to functions expecting the other struct, or use them interchangeably.
Here is an example to illustrate the idea:
struct Base { int commonField; }; struct Derived1 { struct Base base; int additionalField; }; struct Derived2 { struct Base base; float additionalField; }; void printBaseField(struct Base* base) { printf("%d\n", base->commonField); } int main() { struct Derived1 derived1; struct Derived2 derived2; derived1.base.commonField = 10; derived2.base.commonField = 20; printBaseField((struct Base*)&derived1); // Output: 10 printBaseField((struct Base*)&derived2); // Output: 20 return 0; }