function prototypes and parameters
pass by value
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
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
eg 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
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
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 arguments 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.