Function Parameters
Function parameters are like the ingredients you pass to a recipe - they're the values that a function needs to do its job! When you call a function, you can send it data through parameters, making your functions flexible and reusable.
Basic Syntax
return_type function_name(parameter_type parameter_name) {
// function body
return value; // if needed
}
Simple Example
Here's a function that takes two numbers and return the max number:
#include <stdio.h>
int findMaxNumber(int a, int b) {
if(a > b){
return a;
} else {
return b;
}
}
int main() {
int result = findMaxNumber(5, 3);
printf("Result: %d\n", result);
return 0;
}
In this example:
aandbare parameters of thefindMaxNumberfunction5and3are arguments passed when calling the function
Multiple Parameters
Functions can have multiple parameters of different types:
#include <stdio.h>
void displayInfo(char name[], int age, float height) {
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.1f cm\n", height);
}
int main() {
displayInfo("Alice", 25, 165.5);
return 0;
}
Parameter Types
| Parameter Type | Description | Example |
|---|---|---|
| Value Parameters | Copies of the actual values | int x, float y |
| Array Parameters | Arrays passed by reference | int arr[] |
| Pointer Parameters | Memory addresses | int *ptr |
Note: We will learn more about Pointers in upcoming topics.
Pass by Value
In C, most parameters are passed by value, meaning the function gets a copy of the data:
#include <stdio.h>
void modifyValue(int x) {
x = 100; // This only changes the copy
printf("Inside function: %d\n", x);
}
int main() {
int num = 50;
modifyValue(num);
printf("Outside function: %d\n", num); // Still 50!
return 0;
}
Functions with No Parameters
Sometimes functions don't need any input:
#include <stdio.h>
void sayHello(void) { // 'void' means no parameters
printf("Hello, World!\n");
}
int main() {
sayHello(); // No arguments needed
return 0;
}
Key Points to Remember
- Parameters are like variables that receive values from function calls
- The number and type of arguments must match the parameters
- Parameter names are local to the function
- Changes to parameters (pass by value) don't affect the original variables
- Use meaningful parameter names to make your code readable
Parameters make functions powerful and flexible - they're your gateway to writing reusable code that can work with different data each time it's called!