12

Why does this work:

struct person {
    char name[50];
    short mental_age;
} p1 = {"Donald", 4};

But not this:

typedef struct {
    char name[50];
    short mental_age;
} PERSON p1 = {"Donald", 4};

Is there a way that I can make a typedef struct and initialize Donald when I define this struct?

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
yemerra
  • 1,352
  • 4
  • 19
  • 44

2 Answers2

12

typedefs are aliases for other types. What you're doing is creating a convenience typedef. Since the purpose of a typedef is to create type aliases, you can't define a variable using it.

You have to do this:

typedef struct {
    // data
} mytype;

mytype mydata = {"Donald", 4};
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Pedantic, but what you're here is defining a variable, not declaring it. – Ben Mar 12 '16 at 19:57
  • @Ben, yep, you're right. I'm not a native English speaker and, to be honest, I can hardly see the difference between these two words, so I'm sometimes mixing them up. – ForceBru Mar 12 '16 at 20:03
  • @Ben: You are wrong. In C language the concepts of *definition* and *declaration* are not mutually exclusive. *Definition* is just a special kind of *declaration*. So, in his case he is *declaring* a variable `mydata`. That *declaration* of variable `mydata` just happens to be a *definition* at the same time. – AnT stands with Russia Mar 12 '16 at 20:12
  • @AnT, ugh, that sounds _even more_ confusing. I know what a _function declaration_ is, but what about _variable declaration/definition_? Are those different things? – ForceBru Mar 12 '16 at 20:14
  • Okay, after I've read [this](http://stackoverflow.com/q/1410563/4354477), I think both @Ben and @AnT are right: this is a _definition_ while being a _declaration_. But if I wrote `mytype mydata;` first and then `mydata = 1;` (I don't care about types here), then the first would be a declaration, and the second one - a definition. – ForceBru Mar 12 '16 at 20:21
  • 2
    @ForceBru: That's wrong too. `mtype mydata;` is also a *definition* (i.e. it is a *declaration* that happens to be a *definition*). `mydata = 1` has nothing to do with declarations and definitions at all. In a simplistic form, *definition* is a declaration that reserves memory for an object. Whether this object is initialized or not does not matter. – AnT stands with Russia Mar 12 '16 at 20:44
7

The best way, that I know of, is to separate the strict definition from the typedef statement from the struct declaration, similar to:

struct sPerson
{
    char name[50];
    short mental_age;
};

typedef struct  sPerson PERSON;

PERSON  p1 = {"Donald", 4};
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
user3629249
  • 16,402
  • 1
  • 16
  • 17