Monday, January 26, 2009

typedef struct and struct

There are _3_ ways of using struct. (not two as
mentioned in the previous e-mails). Here are all 3 different ways in a
program, with comments. Hope this clears up confusion.

typedef struct {

int data;
int text;
} S1;
// This will define a typedef for S1, in both C and in C++

struct S2 {
int data;
int text;
};
// This will define a typedef for S2 ONLY in C++, will create error in C.


struct {
int data;
int text;
} S3;
// This will declare S3 to be a variable of type struct.
// This is VERY different from the above two.
// This does not define a type. The above two defined type S1 and S2.

// This tells compiler to allocate memory for variable S3

void main()
{
S1 mine1; // this will work, S1 is a typedef.
S2 mine2; // this will work, S2 is also a typedef.
S3 mine3; // this will NOT work, S3 is not a typedef.


S1.data = 5; // Will give error because S1 is only a typedef.
S2.data = 5; // Will also give error because S1 is only a typedef.
S3.data = 5; // This will work, because S3 is a variable.
}
// That's how they different stuff are handy.


also !!!!!!!!!!! This next bit is important for people who using linked
lists etc.

struct S6 {
S6* ptr;
};
// This works, in C++ only.

typedef struct {
S7* ptr;
} S7;
// Although you would think this does the same thing in C OR C++....

// This DOES NOT work in C nor C++ !!!

No comments: