swincas / cookies-n-code

A repo for code review sessions at CAS
http://astronomy.swin.edu.au/
MIT License
31 stars 34 forks source link

typedef struct in C #13

Closed annehutter closed 6 years ago

annehutter commented 6 years ago

I was wondering what is the difference and implications between the following two cases?

typedef struct foo{
    int x;
} foo;

and

typedef struct {
    int x;
} foo;

Is the first one just needed for linked lists?

(@manodeep edited for syntax highlighting)

manodeep commented 6 years ago

I think both the first and second refer (mostly) to the same thing.

struct foo{
    int x;
};
typedef struct foo foo;

This lets you say

foo newvar;

instead of

struct foo newvar;

I think in the second case there is no declaring struct foo something because the struct itself was anonymous. But not totally sure; feel free to play around in godbolt

annehutter commented 6 years ago

Just to clarify both methods allow this declaration foo newvar; However, if working with linked lists, only the first option works (which sort of makes sense as otherwise next is not defined): typedef struct foo{ int x; foo *next; } foo;

I think I don't really understand the concept of namespace ('foo' before the brackets, to my understanding) when there is a typespace ('foo' after brackets) defined? Are there any implications if the struct is anonymous?

manodeep commented 6 years ago

Ahh I see what you mean. Yes you do need a forward declaration

typedef struct foo foo;
struct foo{
    int x;
    foo *ptrtofoo;
};

I think that should work.

(Otherwise, just declare void * ptrtofoo; and then recast to struct foo * as and when necessary)

manodeep commented 6 years ago

Here's the relevant StackOverflow page

Is this okay to close?

manodeep commented 6 years ago

@annehutter I think this issue is resolved; I am closing for now -- please feel free to re-open.