Page 1 of 1

Static Voids after or before int MAIN()?

Posted: Tue Nov 26, 2019 7:02 pm
by DavilaGames
We all know that the main function of the program is int main (). So during the code I create other functions like void MoveSprites(), void CreatePlayer(), and so on.

I can create these functions before or after int main(), and if created after it, I have to set at the beginning of the code static void MoveSprites() and static void CreatePlayer() to be able to use these functions (because it doesn't even compile if not set).

Anyway, so far so good. My question is, when and what is the difference between putting the function before or after int main()? Is there any difference like "the commands you use always come later and the ones you only call once come before" ...?

And when should I use static before the void of the functions I created AFTER int main () ???

Re: Static Voids after or before int MAIN()?

Posted: Tue Nov 26, 2019 10:57 pm
by Chilly Willy
It's fundamental part of C called prototyping. It gives the compiler all the info needed so that when the function is encountered later, it can generate the proper code to call it. If you define the function before it is used (wherever in the code that is), it's self-prototyping - the definition is also the prototype. If you define the function after the function has been used somewhere in the code, you need a prototype header before the usage so the compiler knows how to compile the usage. So like this...

Code: Select all

void foobar(int x); /* prototype header */

...

    /* middle of code somewhere */
    foobar(55);

...

/* even later in code, the definition */
void foobar(int x)
{
   printf("%d\n", x);
}
versus

Code: Select all

void foobar(int x)
{
    printf("%d\n", x);
}

...
    /* much later in code */
    foobar(55);
    
Both are equally valid. This applies to static functions or global. Doesn't matter other than that static can only be called from within this single source file.

Re: Static Voids after or before int MAIN()?

Posted: Wed Nov 27, 2019 2:18 am
by DavilaGames
Yes, now I understand.. thanks for your attention!!!