Throughout the Propeller C - Start Simple [1] lessons, we put our code in the main function. You can also add other functions to your program and call them from the main function, or even make code in one of those functions call another function.
This first example has a function named hello with a print command in its code block. When the code running in the main method sees hello(); it jumps down to the function named hello, executes the statements in its code block, then returns to the main function. There, the program moves on to the next thing, which is a print statement that displays “Hello again!”
/* Function Call.c Send a simple hello message to the console, but use a function to display one of the messages. */ #include "simpletools.h" // Include simpletools void hello(void); // Function prototype int main() // main function { hello(); // Call hello function print("Hello again from main!\n"); // Display message } void hello(void) // Hello function { print("Hello from function!\n"); // Display hello message pause(500); // Pause 1/2 second }
The void hello(void); line above the main function is called a forward declaration. It tells the PropGCC compiler to expect to see a function named hello later in the program.
Function call.c starts in the main function with pause(500). After that, it sees hello(), which tells it to go find the function named hello, do whatever is in its code block, and come back when done. The hello(); in the main function is called a function call.
The actual hello function is the void hello(void) block of code down below the main function. That’s where the program goes when it sees the hello() call, and it executes that one print statement that displays the “Hello from function!” message. After it runs out of statements to execute, the program returns to the hello call in the main function. There, it moves on to the next statement, which is the print command that displays “Hello again from main!”
In the hello function definition, the void to the left of the name means that the function does not send a value back to the function call. The (void) to the right of the function’s name means that the function does not need to receive any values, called parameters, to do its job. We'll look at parameters and return values in the next few lessons.
A function has a code block contained by curly braces { }. A code block can include one or more statements that will execute when the function is called.
You can also get rid of the forward declaration by moving the entire hello function above the main function. That way, the compiler will have seen the hello function itself before it sees the hello() function call inside main.
The great thing about functions are that they are reusable — they can be called over and over again.
Links
[1] https://learn.parallax.com/propeller-c-start-simple