Static Voids after or before int MAIN()?

SGDK only sub forum

Moderator: Stef

Post Reply
DavilaGames
Interested
Posts: 13
Joined: Thu Jul 04, 2019 4:25 am
Location: Juiz de Fora/MG, Brasil
Contact:

Static Voids after or before int MAIN()?

Post by DavilaGames » Tue Nov 26, 2019 7:02 pm

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 () ???
Yuri d´Ávila
DAVILA GAMES
https://www.davilagames.com.br

Chilly Willy
Very interested
Posts: 2984
Joined: Fri Aug 17, 2007 9:33 pm

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

Post by Chilly Willy » Tue Nov 26, 2019 10:57 pm

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.

DavilaGames
Interested
Posts: 13
Joined: Thu Jul 04, 2019 4:25 am
Location: Juiz de Fora/MG, Brasil
Contact:

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

Post by DavilaGames » Wed Nov 27, 2019 2:18 am

Yes, now I understand.. thanks for your attention!!!
Yuri d´Ávila
DAVILA GAMES
https://www.davilagames.com.br

Post Reply