Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing struct code that works both in C and in C++

I am aware of two possible ways to define and use structs:

#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.

like image 209
fredoverflow Avatar asked Oct 29 '11 08:10

fredoverflow


1 Answers

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;
like image 71
Basile Starynkevitch Avatar answered Oct 01 '22 23:10

Basile Starynkevitch