Anonymous types in C - c

I have the following recursive type definitions in C and I am wondering how to get it to work:
typedef int (*foo) (bar *);
typedef foo *bar;
The sizes of the pointers are well known so this should be OK.
I somehow need to forward declare bar as some anonymous type that I can then typedef correctly. Not sure how to do this in C since it isn't a struct
I want to avoid declaring foo as:
typedef int (*foo) (void *)
because then I lose some type checking properties.

There is no forward declaration for typedefs in C, unfortunately.
UPD.
You can create indirectly recursive type as follows:
struct bar;
typedef int (*foo)(struct bar *);
struct bar {
foo f;
};
And then get pointer to function through the field of the argument. But this requires the structure to be allocated somewhere (may be on stack) and additional pointer dereferencing.
int boo(struct bar *bar) {
return (bar->f)(bar); // infinite loop
}
int main(void) {
struct bar baz = { &boo };
return boo(&baz);
}

Related

typedef struct but keep new type namespaced under keyword 'struct'

How can I typedef a struct but still keep the new type namespaced under the keyword 'struct'?
example:
struct foo {
int x;
};
typedef struct foo struct bar;
int main(void) {
struct bar bar;
bar.x = 10;
return 0;
}
but this doesn't work obviously.
Here are the errors if anyone is curious:
main.c:5:20: error: two or more data types in declaration specifiers
typedef struct foo struct bar;
^
main.c:5:27: warning: useless storage class specifier in empty declaration
typedef struct foo struct bar;
^
main.c: In function 'main':
main.c:9:13: error: storage size of 'bar' isn't known
struct bar bar;
How can I typedef a struct but still keep the new type namespaced under the keyword 'struct'?
So, it seems that you want to define a structure alias for another structure type.
This is not possible with typedef as it creates a single word alias. The new alias can't be consisted of multiple white space separated words.
But you can use a single name like struct_bar with struct implemented inside of the name to show that bar is a structure.
#include <stdio.h>
struct foo {
int x;
};
typedef struct foo struct_bar;
int main(void) {
struct_bar bar;
bar.x = 10;
return 0;
}
How can I typedef a struct but still keep the new type namespaced under the keyword 'struct'?.
You cannot. A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. The concept of Namespace as it is defined within C++, is not inherent in C.
So, if you are okay with minor changes in your requirements, instead of doing something unnatural, use a simple typedef:
Instead of this:
struct foo {
int x;
};
do this:
typedef struct {
int x;
}foo;
Then this will work:
typedef foo bar;
int main(void )
{
bar b;
b.x = 10;
return 0;
}
Note: Although namespaces are not inherent in in C, as they are in C++, there are some interpretations eg: as discussed here, that argue the point.
C doesn't have any type of support for namespaces (at least not in the sense that C++ does).
When you create a typedef, the new type name is a single identifier, not multiple words. So struct bar can't be an alias for another type. You would have to call it bar or some other one-word name.
You can't. This isn't how it works.
You cannot "create" a type whose name is more than one word, nor can you refer to a type alias using the keyword struct.
The purpose of writing struct, in this context, is to refer to a struct type by a name that wasn't introduced as an alias. The keyword is there to say that that's what you want to do. But it's not part of the name; it cannot be part of the name.
Fortunately, there's no reason to need or even want this.
I found a solution that works for cygwin:
struct foo {
int x;
};
struct bar {
struct foo;
};

Is it possible to consistently refer to forward-declared and non-forward-declared structs in C?

This doesn't work for foo
struct Foo;
typedef struct
{
int x;
}
Bar;
void foo (Foo *); // unknown type name ‘Foo’
void bar (Bar *);
typedef struct
{
int y;
}
Foo;
This doesn't work for bar
struct Foo;
typedef struct
{
int x;
}
Bar;
void foo (struct Foo *);
void bar (struct Bar *); ‘struct Bar’ declared inside parameter list
typedef struct
{
int y;
}
Foo;
Some of my structs have to be forward-declared, because they are passed as pointers, and some of them have to be not forward-declared, because they are passes as values.
Is there a way to declare types in C such that all function prototypes can consistently always refer to custom types in the same way, regardless of whether they are forward-declared or not?
Your problem is not forward-declared vs. non-forward-declared, it's struct X vs. typedef struct { ... } X.
You can solve this by using struct X only:
struct Foo;
struct Bar
{
int x;
};
void foo (struct Foo *);
void bar (struct Bar *);
struct Foo
{
int y;
};
Once you have that, you can introduce typedef names:
typedef struct Foo Foo;
typedef struct
{
int x;
}
Bar;
void foo (Foo *);
void bar (Bar *);
struct Foo
{
int y;
};
You can't pre-declare typedefs, so we still need a real struct type we can forward to. There's a small inconsistency here: Foo is the same as struct Foo, but there is no struct Bar, only Bar. You can fix that by switching to
typedef struct Bar
{
int x;
}
Bar;
This defines struct Bar and Bar simultaneously.
struct Foo;
Declare a structure named Foo. But, you must declare a typedef Foo of structure named Foo.
#include <stdio.h>
typedef struct Foo Foo;
typedef struct {
int x;
} Bar;
void foo(Foo *);
void bar(Bar *);
struct Foo {
int y;
};
int main(void) {
printf("Hello, world!\n");
}
The first order of business is to point out that in your examples there is no struct Foo. There is only a struct without a tag that you typedef as Foo.1
Is there a way to declare types in C such that all function prototypes can consistently always refer to custom types in the same way, regardless of whether they are forward-declared or not?
The definition or declaration of the struct should appear before the struct is used in a function parameter list. Otherwise the declarations scope is only the function prototype, which is almost certainly not what you want.
The way to achieve what you want is only through disciplined coding.
A forward declaration is all you ever really need for a function prototype. You don't need the full struct definition until the function itself is defined or called.
struct Foo;
void foo (struct Foo); // Okay, only at the call site or definition site
// do we need the full struct definition.
A short example to demonstrate
#include <stdio.h>
struct Foo;
void foo (struct Foo);
struct Foo
{
int y;
};
int main(void) {
struct Foo f = { .y = 1 };
foo(f);
return 0;
}
void foo (struct Foo f)
{
printf("%d", f.y);
}
It's much clearer that it's okay when the definitions and declarations are spread out among different translation units, but the above will have to do.
So what I suggest to you, is that you always forward declare your structs on a separate line, before they are to be used in function prototypes (by pointer or by value). And refrain from introducing the full definition until it's really needed.
1 A lovely correspondence on fa.linux.kernel where Linus Torvalds articulates far better than me why you should prefer to use the full struct tag.
The only "forward declaration" and reference supported by C is the pointer, e.g.:
void myFunc (struct XYZ *p);
This tells the compiler you are referring to a type struct XYZ, possibly not yet declared, of which you are passing a pointer. This allows the compiler to perform type checking without knowing what this structure actually consists of.
Note that pointers are all the same size, so there is no check on the pointer itself, just on the thing it is pointing to.
See also other solutions that explain using typedef.
You mix up forward declaration and type definitions. Both are different things. If you want to have the same kind of usage of forward declared structs do it:
struct Foo; // forward declaration
struct Bar { int x; }; // definition
void foo(struct Foo); // works for a prototype
void bar(struct Bar); // works for a prototype
You cannot forward declare type definitions. Maybe this is the reason for the name definition. However, you can type define a forward declaration:
struct Foo; // forward declaration
typedef struct Foo Foo_t; // type definition of a forward declaration
struct Bar { int x; }; // definition
typedef struct Bar Bar_t; // type definition of a definition
void foo(Foo_t); // works
void bar(Bar_t); // works
If you have a function definition the type has to be completed. This means that you have already defined the forward declared type at this location or that you have to use pointers. Again: It does not matter, whether you use structures or type definitions.
BTW: As you can see in my examples, it is an urban legend that incomplete structure types has to be passed "by reference". You can use the incomplete type in the function declaration (prototype). However, when you define the function, the type has to be completed. This is no deal in most cases.

How declare extern struct?

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.

Why does forward declaration of struct not work?

I wrote a small code in C in which two struct types were defined which have members of each other in their definition. Case 1: If the struct foo is defined before struct bar, the code is compiled as expected. Case 2: If struct foo is defined after struct bar it will not compile which is also expected as there is no way to know the memory requirement of a struct foo variable. But I was expecting it will compile if a forward declaration of struct foo is used in case 2. But it does not work. What am I missing?
#include<stdio.h>
#include<stdlib.h>
struct foo; // forward declaration
struct bar
{
int a;
struct bar *next;
struct foo ch;
};
struct foo
{
struct bar *n;
struct foo *nx;
};
int main()
{
struct bar p;
return(0);
}
forward declaration only informs the compiler that there is something that is called foo it does nothing says about size.
you can use foo* since this is a pointer of known size but not foo itself because the size is unknwon, so the compiler does not know how the memory layout of barshould look like.
And the compiler only do a single pass through your document. so it cannot know the strucutre that is defined ahead.
If a struct type X appears only as a pointer type in a structure declaration or its functions, and the code in the header file does not attempt to access any member variables of X, then you should not #include X.h, but instead make an incomplete declaration of X (also called a
"forward" declaration) before the first use of X. Here is an example in which a structure type Thing refers to X by a pointer:
struct X; /* incomplete ("forward") declaration */
struct Thing {
int i;
struct X* x_ptr;
};
The compiler will be happy to accept code containing pointers to an incompletely known structure type, basically because pointers always have the same size and characteristics regardless of what they are pointing to. Typically, only the code in the .c file needs to access the members (or size) of X, so the .c file will #include "X.h". This is a powerful technique for encapsulating a module and decoupling it from other modules.
That is, it would work correctly if your code was something like :
#include<stdio.h>
#include<stdlib.h>
struct foo; // forward declaration
struct bar
{
int a;
struct bar *next;
struct foo *ch; /* MODIFIED LINE */
};
struct foo
{
struct bar *n;
struct foo *nx;
};
int main()
{
struct bar p;
return(0);
}
But in your case, struct bar is having an "element" of type struct foo. Hence it will give error field has incomplete type.
Also for your information, see the below snippet (will work perfectly):
#include<stdio.h>
#include<stdlib.h>
struct bar
{
int a;
struct aabar *next; /* MODIFIED LINE - aabar never declared */
struct foo *ch;
};
struct foo
{
struct bar *n;
struct foo *nx;
};
int main()
{
struct bar p;
return(0);
}
A declaration also can't let the compiler know how to allocate the memory.
In your struct foo the element nx is a pointer, so defining struct foo doesn't require memery size. However, on struct bar the element ch is not a pointer, so the defining struct bar needs to know the size of struct foo. The forward declaration doesn't specify the memory size, the definition does.

What's the syntactically proper way to declare a C struct?

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;

Resources