DEV Community

Cover image for Functions in C Programming
sarancs
sarancs

Posted on • Edited on

Functions in C Programming

Why are functions actually Used ?

Whenever, we're using a Block of code continuously for a lot of iterations then we needn't repeat the whole code in the main() Function of C.

#include

int main()
{
int num;
scanf("%d",&num);

if(num == 0)
    printf("Neither positive nor negative\n");
else if(num > 0)
    printf("Positive\n");
else
    printf("Negative\n");

scanf("%d",&num);
if(num == 0)
    printf("Neither positive nor negative\n");
else if(num > 0)
    printf("Positive\n");
else
    printf("Negative\n");

return 0;
Enter fullscreen mode Exit fullscreen mode

}
This is an Example code without using Functions.

In the above code, We're using the block of code from if-else. This repetitive usage of the same block makes the code hard to navigate through and makes it hard to understand.

So instead we can use functions to avoid repetition of the same block of code.

Now, as we Understood the Limitations. Let's see How to Declare a Function ?

Syntax of a Declaring a Function in C :
return_type function_name( parameter list ) {
body of the function
}

Now, Let's see what a Function is ?

A function definition in C programming consists of a function header and a function body.

Return Type

  • A function has a return value that is the value that is returned to the calling part in any other function.
  • The Reuturn type is defined in the Function declaration itself.
  • Example: int check(int a );-> in the given Example the return type is integer data type.

Function Name

  • This is the name of the function which the user will be giving.
  • It is the name by which it'll called and referred to.

Parameters

  • The parameters refers to the type, order, and number of the parameters of a function.
  • Parameters are optional that is, even if Parameters aren't present in the Function it'll run.
  • These are the values that a function that is being called to takes.

Function Body

  • The function body contains statements that tell the function what should be done.

Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.

#include

void check(int n)
{
if(n == 0)
printf("Neither positive nor negative\n");
else if(n > 0)
printf("Positive\n");
else
printf("Negative\n");
}

int main()
{
int n;
scanf("%d",&n);
check(n);

scanf("%d",&n);
check(n);

return 0;
Enter fullscreen mode Exit fullscreen mode

}

Example Code using Function

As we can see in the example code, that using a function makes it more readable to the user and simplifies the process of navigating.

Top comments (0)