I have a bit of confusion between the below declarations - could you please help clear it up?
typedef struct {
int a;
int b;
} example;
And this
struct something {
int a;
int b;
} ob;
And I am not sure what the below would even mean?
typedef struct foo {
int a;
int b;
} bar;
typedef struct {
int a;
int b;
} example;
This one defines an unnamed structure type and introduces example as a type alias for that structure type. You can therefore refer to that structure type only as `example.
struct something {
int a;
int b;
} ob;
This one defines a structure type something and also declares an object ob of that type. You can refer to the structure type only as struct something.
typedef struct foo {
int a;
int b;
} bar;
This one defines a structure type named foo and introduces bar as a type alias for that structure type. You can refer to that structure type as struct foo or as bar.
With
typedef struct {
int a;
int b;
} example;
you define an unnamed structure, but define a type-alias example for the structure. That means you can only create instance of the structures using the example "type", like e.g.
example my_example_structure;
With
struct something {
int a;
int b;
} ob;
you define a structure named something, and an instance (a variable) of that structure named ob. You can use struct something to create new variables of the structure:
struct something my_second_ob;
The variable ob can be used like any other instance of the structure:
printf("b = %d\n", ob.b);
Lastly, with
typedef struct foo {
int a;
int b;
} bar;
you define a structure named foo, so you can use e.g. struct foo to define variables. You also define a type-alias bar which can also be used. Like for example
struct foo my_first_foo;
bar my_second_foo;
The general syntax for typedef is
typedef <actual type> <alias name>;
In the last case of your examples, the <actual type> is
struct foo {
int a;
int b;
}
and the <alias name is bar.
Related
I can using struct in now defining struct but how declare function or struct dependencing tohether?
test.h
extern struct foo;
typedef int (*test)(FOO *f);
typedef struct foo
{
char a;
test *t;
} FOO;
int haha(FOO *f) { return 0;}
typedef struct foo
{
char a;
test *t;
} FOO;
test.c
int main() {FOO e; return 0; }
The problem is that you can not define a structure variable (or member inside another structure) unless you have the full definition of the actual structure. Forward declarations are not full definitions. If you have a forward declaration all you can declare is a pointer to the structure.
That means all you can do is something like
typedef struct bar BAR; // Forward declaration of the structure and type-alias definition in one line
typedef struct foo FOO; // Forward declaration of the structure and type-alias definition in one line
struct foo {
char a;
BAR *b; // Define a *pointer* to the BAR structure
FOO *s; // Define a *pointer* to the FOO structure
};
This works because to declare a pointer to a structure, the compiler only has to know that the structure exists, it doesn't need the full structure definition. For this a normal forward declaration is all you need.
Also note that when referencing a structure recursively a pointer is needed too, because the full definition is not complete until the closing brace.
I have a struct declaration in C that looks something like this:
static struct {
int a;
int b;
} myStruct[10];
I want to declare a struct member variable inside myStruct, so I try to add this:
static struct {
int c;
int d;
struct myStruct[10] s;
} myNestedStruct[100];
I'm getting a bunch of errors i.e. syntax error before or at: [ and
syntax requires ";" after last struct/union member. What would the better way to implement the nested structs be?
EDIT: My code now looks like this:
static struct {
int a;
int b;
} myStruct[10];
static struct {
int c;
int d;
struct myStruct s[10];
} myNestedStruct[100];
However I'm getting an error: incomplete struct/union/enum myStruct: s
You need to declare myStruct first before using it as a struct type.
struct myStruct {
int a;
int b;
};
static struct {
int c;
int d;
struct myStruct s[10];
} myNestedStruct[100];
This creates a variable called myNestedStruct which is an array of 100 structs, each containing two ints and an array of 10 mystructs.
When you write code like
struct { ... } Foo;, it's not declaring a type named Foo but a variable. Its type is an anonymous struct corresponding to what you put in the curly braces. If you want to declare a type, write struct Foo { ... };.
That's where your error is coming from -- myStruct is not a type name, so when you write struct myStruct in the definition of myNestedStruct the compiler thinks you're about to define a struct by that name. But then it encounters an [ which shouldn't be the next token in a struct declaration ever so it tells you can't make sense of the code.
If I have these two structs:
struct
{
int x;
} A;
struct
{
int x;
} B;
then making A = B; results in a compilation error because the two anonymous structs are not compatible.
However if I do:
typedef struct
{
int x;
} S;
S A;
S B;
A = B; is a legal assignment because they are compatible.
But why? With typedef I understand that the compiler makes this when meet S A and S B:
struct { int x; } A;
struct { int x; } B;
so A and B should not be compatible...
Each anonymous struct declaration is a distinct type; this is why you get a type mismatch when trying to assign one to the other.
A typedef, however, declares an alias (i.e. a new name for something that already exists) for a type (it does not create a new type).
A typedef is also not a simple text replacement, like a preprocessor macro. Your statement
I understand that the compiler make this when meet S A and S B:
struct { int x; } A;
struct { int x; } B;
is where your understanding is wrong.
When you use the type alias S, as in
S A;
S B;
the types of both objects A and B are the same by definition and assigning one to the other is possible.
This is because C treats every untagged struct as a new kind of struct, regardless of the memory layout. However, typedef struct { } name; cannot be used if you want to use the struct in a linked list. You'll need to stick with defining a structure tag in this case, and typedef the tagged struct instead.
struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
};
struct VolumeInCC /* Anonymous 2 */
{
int x; /* volume */
};
struct DistanceInMeter A;
struct VolumeInCC B;
...
A = B; /* Something is wrong here */
Equating different type doesn't always make sense and thus is not allowed.
typedef struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
} Dist_t;
Dist_t C, D;
...
C = D; /* Alright, makes sense */
If I have an arbitrary struct, is there any way that I can use a macro to add a field to that struct?
for example:
struct foo{
int a,
int b
};
MAGIC(foo, newtype, newname);
Which would evaluate to:
struct foo{
int a;
int b;
};
struct magic_foo{
int a;
int b;
newtype newname;
};
I know this is a stretch, but I'm thinking there might be some built in macro that retrieves the definition of a struct from it's name?
Not directly, since the preprocessor is completely unaware of the C syntax (it operates only as a token replacer; introspection for previously declared types is impossible).
Maybe this is a way to go:
#define STRUCT { \
int a; \
int b; \
EXTRA_MEMBER_DECL \
}
#define EXTRA_MEMBER_DECL /* empty */
struct foo STRUCT;
#define EXTRA_MEMBER_DECL newtype newname;
struct bar STRUCT;
Plan B could be using a nested struct:
struct bar {
struct foo;
newtype newmember;
};
I've seen C structs declared several different ways before. Why is that and what, if anything, does each do different?
For example:
struct foo {
short a;
int b;
float c;
};
typedef struct {
short d;
int e;
float f;
} bar;
typedef struct _baz {
short a;
int b;
float c;
} baz;
int main (int argc, char const *argv[])
{
struct foo a;
bar b;
baz c;
return 0;
}
Well, the obvious difference is demonstrated in your main:
struct foo a;
bar b;
baz c;
The first declaration is of an un-typedefed struct and needs the struct keyword to use. The second is of a typedefed anonymous struct, and so we use the typedef name. The third combines both the first and the second: your example uses baz (which is conveniently short) but could just as easily use struct _baz to the same effect.
Update: larsmans' answer mentions a more common case where you have to use at least struct x { } to make a linked list. The second case wouldn't be possible here (unless you abandon sanity and use a void * instead) because the struct is anonymous, and the typedef doesn't happen until the struct is defined, giving you no way to make a (type-safe) pointer to the struct type itself. The first version works fine for this use, but the third is generally preferred in my experience. Give him some rep for that.
A more subtle difference is in namespace placement. In C, struct tags are placed in a separate namespace from other names, but typedef names aren't. So the following is legal:
struct test {
// contents
};
struct test *test() {
// contents
}
But the following is not, because it would be ambiguous what the name test is:
typedef struct {
// contents
} test;
test *test() {
// contents
}
typedef makes the name shorter (always a plus), but it puts it in the same namespace as your variables and functions. Usually this isn't an issue, but it is a subtle difference beyond the simple shortening.
It's largely a matter of personal preference. I like to give new types a name starting with a capital letter and omit the struct, so I usually write typedef struct { ... } Foo. That means I cannot then write struct Foo.
The exception is when a struct contains a pointer to its own type, e.g.
typedef struct Node {
// ...
struct Node *next;
} Node;
In this case you need to also declare the struct Node type, since the typedef is not in scope within the struct definition. Note that both names may be the same (I'm not sure where the underscore convention originated, but I guess older C compilers couldn't handle typedef struct X X;).
All your uses are syntactically correct. I prefer the following usage
/* forward declare all structs and typedefs */
typedef struct foo foo;
.
.
/* declare the struct itself */
struct foo {
short a;
int b;
foo* next;
};
Observe that this easily allows to use the typedef already inside the declaration of the struct itself, and that even for struct that reference each other mutually.
The confusion comes about because some of the declarations are in fact declaring up to three C constructs. You need to keep in mind the difference between:
A typedef declaration,
A struct definition, and
A struct declaration.
They are all very different C constructs. They all do different things; but you can combine them into the one compound construct, if you want to.
Let's look at each declaration in turn.
struct foo {
short a;
int b;
float c;
};
Here we are using the most basic struct definition syntax. We are defining a C type and give it the name foo in the tag namespace. It can later be used to declare variables of that type using the following syntax:
struct foo myFoo; // Declare a struct variable of type foo.
This next declaration gives the type another name (alias) in the global namespace. Let's break it down into its components using the previous basic declaration.
typedef foo bar; // Declare bar as a variable type, the alias of foo.
bar myBar; // No need for the "struct" keyword
Now just replace "foo" with the the struct's definition and voila!
typedef struct {
short d;
int e;
float f;
} bar;
typedef struct _baz {
short a;
int b;
float c;
} baz;
The above syntax is equivalent to the following sequence of declarations.
struct _baz {
short a;
int b;
float c;
}
typedef _baz baz; // Declare baz as an alias for _baz.
baz myBaz; // Is the same as: struct _baz myBaz;