Smiley7
Smiley7

Reputation: 235

Struct definition and setting member of struct

I wanted to understand why with this struct definition, we can directly use the name event to assign values to structure members. I have seen other definitions, where struct keyword is used to assign values.

struct {
    int eventNum;
    int eventType;
} event;

void function() {
    event.eventNum = 10; 
}

Upvotes: 3

Views: 528

Answers (3)

0___________
0___________

Reputation: 68013

you declare the global variable event which type is a "tagless" or "incomplete" (this is the question for the language lawyers how to call it properly) structure struct { int ventNum; int eventType; }. As it is the global variable, it is visible in the scope of entire program including your function

Upvotes: -1

chqrlie
chqrlie

Reputation: 145297

In your code fragment, event is an instance of an unnamed structure, an uninitialized global variable. At global scope, uninitialized objects have all members initialized to the zero value for their type.

The function function() can use the event name to refer to this object and assign a value to one of its members: event.eventNum = 10;.

You may have seen initialized structure definitions like this:

struct {
    int eventNum;
    int eventType;
} event = { 10, 0 };

Or C99 specific initalizers like this:

struct {
    int eventNum;
    int eventType;
} event = { .eventNum = 10 };

These definitions can occur at global or local scope and define an initialized object event.

Upvotes: 4

ForceBru
ForceBru

Reputation: 44906

struct Name {int stuff; int data;} variable;

It's just the same thing as, for example, int variable;, so, this is an ordinary variable, but with a complex, or, as pointed out in the comments, a derived type.

Upvotes: 4

Related Questions