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 () ???
Static Voids after or before int MAIN()?
Moderator: Stef
-
- Interested
- Posts: 13
- Joined: Thu Jul 04, 2019 4:25 am
- Location: Juiz de Fora/MG, Brasil
- Contact:
-
- Very interested
- Posts: 2984
- Joined: Fri Aug 17, 2007 9:33 pm
Re: Static Voids after or before int MAIN()?
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...
versus
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.
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);
}
Code: Select all
void foobar(int x)
{
printf("%d\n", x);
}
...
/* much later in code */
foobar(55);
-
- 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()?
Yes, now I understand.. thanks for your attention!!!