In C programming, functions are the building blocks of larger programs. They allow you to group code for reusability, break down complex tasks and pass data around.
Syntax:
returnType functionName(){
...
...
}
If a function doesn't return any value use void.
Example:
#include <stdio.h>
void greet(){
printf("Good Morning\n");
}
int main() {
greet();
greet();
greet();
return 0;
}
Function with parameters
In C programming, function parameters are used to pass values or references to a function when it is called. Function parameters allow you to make your functions more flexible and reusable by accepting different inputs.
Syntax:
return_type function_name(parameter_type parameter_name1, parameter_type parameter_name2, ...);
Example:
#include <stdio.h>
void addNumbers(double number1, double number2){
double sum = number1 + number2;
printf("Sum of %.2lf and %.2lf is %.2lf", number1, number2, sum);
}
int main() {
addNumbers(8.9, 9.6);
return 0;
}
return type
- If function doesn't return any value use void.
- Datatype of the return value and the datatype of the variable where the return value is stored should be the same.
- Anything after the return statement in the function will not be executed.
#include <stdio.h>
double addNumbers(double number1, double number2){
double sum = number1 + number2;
return sum;
}
int main() {
double result = addNumbers(8.9, 9.6);
printf("Result = %.2lf", result);
return 0;
}
Function prototype
Function prototype is a declaration of a function. it provides information about the function name, parameters and return types, but it doesn't include the body.
Example:
#include <stdio.h>
//below function prototype.
double addNumbers(double number1, double number2);
int main() {
double result = addNumbers(8.9, 9.6);
printf("Result = %.2lf", result);
return 0;
}
double addNumbers(double number1, double number2){
double sum = number1 + number2;
return sum;
printf("After return statement");
}
In our program we are calling the function before defining the function(that means, creating function after the main function of c.). In this type of situation the function prototype provide information about the function to the compiler.
If we are defining the function before the function call a function prototype is not needed.
Top comments (0)