Function prototypes and parameters (pass by value).
Lesson 3.2: Function Prototypes and Parameters (Pass by Value)
In this lesson, you'll dive deeper into the mechanics of functions, exploring how to declare them properly, pass information to them, and understand how C handles function arguments.
1. Function Prototypes (Declarations)
What is a Function Prototype?
A function prototype is essentially a declaration of a function. It tells the compiler about the function's existence, its name, return type, and the types of parameters it expects.
Why are Prototypes Important?
Type Checking: The compiler uses the prototype to check if your function calls are correct (e.g., that you're passing the right number and types of arguments).
Early Declaration: Prototypes allow you to define the main logic of your program first (main function) and place function definitions later in the code. This makes your code more readable and organized.
Syntax:
C
<return type> functionName(parameter type1, parameter type2, ...);
Example:
C
int addNumbers(int num1, int num2); // Function prototype for a function that adds two integers
2. Function Parameters
What are Parameters?
Parameters are variables declared in the function prototype and definition that receive values from the function call.
They act as placeholders for the actual values you want the function to work with.
Pass by Value
In C, function parameters are passed by value by default.
This means a copy of the argument's value is made and passed into the function.
Any modifications made to the parameter inside the function do not affect the original variable in the calling code.
This is important for preserving the integrity of your data outside the function.
Example:
C
#include <stdio.h>
void modifyValue(int num) {
num = num * 2; // Modify the local copy of 'num'
printf("Inside function: num = %d\n", num);
}
int main() {
int x = 5;
printf("Before calling function: x = %d\n", x);
modifyValue(x); // Pass a copy of 'x'
printf("After calling function: x = %d\n", x); // 'x' remains unchanged
return 0;
}
Output:
Before calling function: x = 5
Inside function: num = 10
After calling function: x = 5
Key Points:
Function Prototype: Declare functions before they are used to ensure proper type checking.
Pass by Value: C passes arguments by value by default, meaning modifications inside the function do not affect the original variables.
Hands-On Exercise:
Create a function calculateCircleArea that takes the radius of a circle as a parameter and returns the area.
In the main function, prompt the user to enter a radius.
Call calculateCircleArea to calculate the area and display the result to the user.