Defining multiple parameters
What you'll learn: How to design functions that accept more than one piece of information to perform more complex tasks.
The multi-slotted machine
In previous lessons, we looked at functions that take a single value. However, most real-world tasks require several inputs to work correctly. Think of a function like a specialized vending machine. A machine that only takes a coin (one parameter) can only do one thing. But a machine that takes a coin, a row number, and a column letter (three parameters) can give you exactly the snack you want.
In C, you aren't limited to one input. You can define as many parameters as you need, provided you tell the compiler exactly what type of data each one represents.
Setting the blueprint
To define a function with multiple parameters, you list them inside the parentheses, separated by commas. Each parameter must have its own data type and a unique name.
Imagine you are writing a program for a construction company to calculate the area of a rectangular floor. You need two pieces of information: the width and the height.
#include <stdio.h>
// This function defines two integer parameters: w and h
void printArea(int w, int h) {
int area = w * h;
printf("The total area is: %d square meters\n", area);
}
int main() {
// We pass two arguments, separated by a comma
printArea(5, 10);
return 0;
}
The Golden Rule: Order Matters
When you define a function as void printArea(int w, int h), C creates two "slots" in that specific order. When you call the function later with printArea(5, 10), the computer automatically assigns 5 to w and 10 to h.
If you were to create a function that takes different types—for example, an int for an age and a float for a bank balance—you must pass the values in that exact sequence. If you mix them up, the computer will try to put the decimal number into the integer slot, which leads to bugs or "chopped off" data.
Think of it like a mailing address: the Zip Code and the House Number are both numbers, but if you swap their positions on the envelope, the letter won't arrive at the right destination.
Key takeaway
To define multiple parameters, list them inside the parentheses separated by commas, ensuring you provide a type and name for each, and always pass your arguments in the matching order.