-1

I tried typing the following code in a simple C project, but it keeps saying that MyStruct is undefined – unless I add struct before every MyStruct (i.e. struct MyStruct my_struct; which just feels wrong?).

struct MyStruct {
    int my_int;
}

int main() {
    MyStruct my_struct;
    my_struct->my_int = 1;

    return 0;
}
Matt
  • 162
  • 1
  • 8

1 Answers1

1

It’s not wrong, it’s the way C works. Type name is struct MyStruct (it would be simply MyStruct in C++). If you feel that inconvenient, make a typedef, like:

typedef struct MyStruct { ... } MyStruct;

That may or may not be considered a good practice, though.

Also note that a struct (but not a typedef) and a function can have the same name (without the struct prefix). sigaction is a real-word example of that.

numzero
  • 2,009
  • 6
  • 6
  • Very useful! I guess I'm too used to C++. This is for a C assignment, though, so I guess getting used to writing `struct MyStruct` would be better practice to remind myself of how C differs from C++. – Matt Apr 26 '20 at 19:45