Search code examples
cstructtypedef

Defining structs in C after main() function


I have learned a decent amount of java and now I want to learn C, I've learned a little about structs and typedefs but I have errors when I place the typedef after the main() function and it is used from within the main() function.

Is there a way to declare types but not define them in C so I can keep my code after the main() function similar to functions? (I'm not sure if this is good practice but I like organizing my code this way)


Solution

  • Don't do that. C code is intended to be read by the compiler and it will learn about new definitions as it keeps reading the file. Moving things below main() serves no purpose. It will also confuse other humans.

    As for the question itself: in some cases, yes, you can. If everything you need is a forward declaration, you can do so. But in most cases you will want the definition, so it won't help you.

    For example, this will compile:

    struct T;
    
    int main(void)
    {
        struct T * p = 0;
        return !!p;
    }
    
    // Later on you may define `struct T`