Many functions are designed to receive values that they need to do their jobs. These values are called parameters.
- Use the Open Project button to open Function with Parameter.side.
- Read the code. What do you think it will do?
- Click the Run with Terminal button, and compare the result from the Propeller with your prediction.
/* Function with Parameter.c Call a function that displays a value passed to it with a parameter. */ #include "simpletools.h" // Include simpletools void value(int a); // Function prototype int main() // main function { value(6); // Call value function } void value(int a) // value function { print("The value is: a = %d\n", a); // Display a single value }
How it Works
First we see the function definition void value(int a). Remember, the void on the left means this function does not send back a return value to function calls. The (int a) on the right means that it expects to receive an int value from function calls.
In main, the function call value(6) passes the value 6 to the function. The value function receives the value 6, stores it in the int variable named a. Then, the value function's code block displays that value with print("The value is: %d\n", a).
Did You Know?
- Local variables — The int variable a that gets declared as a parameter in the value function definition is called a local variable. It is used only inside this function, and memory is reserved for it only while this function is running. Your program could have other functions with their own local variables named a. They won't interfere with each other.
- Multiple local variables — You can expand a function definition to receive more values by adding more parameters. Each parameter in a function definition should be separated by a comma and each needs a unique name.
Try This
Let's define a function named values that has two parameters.
- Click the Save Project As button and save your project as Functions with Parameters.
- Modify the program using the example below.
- Examine the program and predict what it will display.
- Click the Run Project with Console button, and check what the program does against your predictions.
Did you notice that both function definitions include a parameter named a, and that they do not interfere with each other?
Your Turn
- Write a function definition of void counter(int startVal, int endVal, int incVal)
- Add a for loop to the function that starts counting at startVal, stops counting at endVal, and takes steps of incVal. HINT: Your for loop should start with for(int i = startVal;...