I am aware of two possible ways to define and use struct
s:
#1
struct person
{
char name[32];
int age;
};
struct person dmr = {"Dennis Ritchie", 70};
#2
typedef struct
{
char name[32];
int age;
} person;
person dmr = {"Dennis Ritchie", 70};
The interesting property of the first way is that both the type and the variable can have the same name:
struct person person = {"Sam Persson", 50};
Is that idiomatic in C? Is it guaranteed to work in C++? Or are there corner cases I should be aware of?
Note that I am not interested in pure C++ answers (e.g. "use std::string
instead of char[32]
"). This is a question about C/C++ compatibility.
struct
are compatible between C & C++ only when they are POD-s.
I tend to code something like:
struct person_st { char name[32]; int age; };
typedef struct person_st Person_t;
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