DEV Community

Sujith V S
Sujith V S

Posted on • Updated on

Functions in C programming.

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(){
...
...
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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, ...);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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)