Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

C Functions

C Functions
A function in C is a set of statements that when called perform some specific task. It is the basic
building block of a C program that provides modularity and code reusability. The programming
statements of a function are enclosed within { } braces, having certain meanings and performing
certain operations. They are also called subroutines or procedures in other languages.

In this article, we will learn about functions, function definition. declaration, arguments and
parameters, return values, and many more.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:

1. Function Declaration
2. Function Definition
3. Function Calls

Function Declarations
In a function declaration, we must provide the function name, its return type, and the number and
type of its parameters. A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2 );

The parameter name is not mandatory while declaring functions. We can also declare the function
without using the name of the data variables.

Example

int sum(int a, int b);

int sum(int , int);

Function Declaration
Note: A function in C must always be declared globally before calling it.

Function Definition
The function definition consists of actual statements which are executed when the function is called
(i.e. when the program control comes to the function).

A C function is generally defined and declared in a single step because the function definition always
starts with the function declaration so we do not need to declare it explicitly. The below example
serves as both a function definition and a declaration.

return_type function_name (para1_type para1_name, para2_type para2_name )

{
// body of the function

Function Definition in C

Function Call
A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.

In the below example, the first sum function is called and 10,30 are passed to the sum function.
After the function call sum of a and b is returned and control is also returned back to the main
function of the program.

Working of function in C
Note: Function call is neccessary to bring the program control to the function
definition. If not called, the function statements will not be executed.

Example of C Function
// C program to show function
// call and definition
#include <stdio.h>

// Function that takes two


parameters
// a and b as inputs and
returns
// their sum
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add
variable
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
}

Output
Sum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and called the
function.

Function Return Type

Function return type tells what type of value is returned after all function is executed. When we
don’t want to return a value, we can use the void data type.

Example:

int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.

Note: Only one value can be returned from a C function. To return multiple values, we
have to use pointers or structures.

Function Arguments

Function Arguments (also known as Function Parameters) are the data that is passed to a function.

Example:
int function_name(int var1, int var2);

Conditions of Return Types and Arguments


In C programming language, functions can be called either with or without arguments and might
return values. They may or might not return values to the calling functions.

1. Function with no arguments and no return value


2. Function with no arguments and with return value
3. Function with argument and with no return value
4. Function with arguments and with return value
To know more about function Arguments and Return values refer to the article – Function
Arguments & Return Values in C.

How Does C Function Work?


Working of the C function can be broken into the following steps as mentioned below:

1. Declaring a function: Declaring a function is a step where we declare a function. Here we


define the return types and parameters of the function.
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the function by passing the
arguments in the function.
4. Executing the function: Executing the function is a step where we can run all the statements
inside the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value after the
execution of the function is returned. Exiting the function is the final step where all the allocated
memory to the variables, functions, etc is destroyed before giving full control to the main
function.

Types of Functions
There are two types of functions in C:

1. Library Functions
2. User Defined Functions

Types of Functions in C
1. Library Function

A library function is also referred to as a “built-in function”. A compiler package already exists that
contains these functions, each of which has a specific meaning and is included in the package. Built-
in functions have the advantage of being directly usable without being defined, whereas user-defined
functions must be declared and defined before being used.

For Example:

pow(), sqrt(), strcmp(), strcpy() etc.


Advantages of C library functions
 C Library functions are easy to use and optimized for better performance.
 C library functions save a lot of time i.e, function development time.
 C library functions are convenient as they always work.
Example:

// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf


= %.2lf",
Number, squareRoot);
return 0;
}

Output
The Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions or “tailor-made
functions”. User-defined functions can be improved and modified according to the need of the
programmer. Whenever we write a function that is case-specific and is not defined in any header
file, we need to declare and define our own functions according to the syntax.

Advantages of User-Defined Functions


 Changeable functions can be modified as per need.
 The Code of these functions is reusable in other programs.
 These functions are easy to understand, debug and maintain.
Example:

// C program to show
// user-defined
functions
#include <stdio.h>

int sum(int a, int b)


{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d",


res);
return 0;
}

Output
Sum is: 70

Passing Parameters to Functions


The data passed when the function is being invoked is known as the Actual parameters. In the below
program, 10 and 30 are known as actual parameters. Formal Parameters are the variable and the
data type as mentioned in the function declaration. In the below program, a and b are known as
formal parameters.

Passing Parameters to Functions

We can pass arguments to the C function in two ways:

1. Pass by Value
2. Pass by Reference
1. Pass by Value

Parameter passing in this method copies values from actual parameters into formal function
parameters. As a result, any changes made inside the functions do not reflect in the caller’s
parameters.

Example:

// C program to show use


// of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2
is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swap Value of var1 and var2
is: %d, %d",
var1, var2);
return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2

2. Pass by Reference

The caller’s actual parameters and the function’s actual parameters refer to the same locations, so
any changes made inside the function are reflected in the caller’s actual parameters.

Example:

// C program to show use of


// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)


{
int temp = *var1;
*var1 = *var2;
*var2 = temp;
}
// Driver code
int main()
{
int var1 = 3, var2 = 2;
printf("Before swap Value of var1 and var2
is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swap Value of var1 and var2
is: %d, %d",
var1, var2);
return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3

Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned below:

1. The function can reduce the repetition of the same statements in the program.
2. The function makes code readable by providing modularity to our program.
3. There is no fixed number of calling functions it can be called as many times as you want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking about the internal working
of the function.

Disadvantages of Functions in C
The following are the major disadvantages of functions in C:

1. Cannot return multiple values.


2. Memory and time overhead due to stack frame allocation and transfer of program control.

Conclusion
In this article, we discussed the following points about the function as mentioned below:

1. The function is the block of code that can be reused as many times as we want inside a
program.
2. To use a function we need to call a function.
3. Function declaration includes function_name, return type, and parameters.
4. Function definition includes the body of the function.
5. The function is of two types user-defined function and library function.
6. In function, we can according to two types call by value and call by reference according to
the values passed.

FAQs on Functions in C

Q1. Define functions.

Answer:
Functions are the block of code that is executed every time they are called during an
execution of a program.

Q2. What is a forward declaration?

Answer:

Sometimes we define the function after its call to provide better readibliy. In such
cases, we declare function before the their defiinition and call. Such declaration are
called Forward Declaration.

Q3. What is the difference between function declaration and definition?

Answer:

The data like function name, return type, and the parameter is included in the
function declaration whereas the definition is the body of the function. All these data
are shared with the compiler according to their corresponding steps.

Q4. What is the difference between function arguments and parameters?

Answer:

Function parameters are the values declared in a function declaration. Whereas,


function arguments are the values that are passed in the function during the function
call.

Example:
int func(int x,int y);func(10,20);

Here, int x and int y are parameters while, 10 and 20 are the arguments passed to
the function.

To know more about it, refer to this article – Difference between Arguments and
Parameters in C.

Q5. Can we return multiple values from a C Function?

Answer:

No, it is generally not possible to return multiple values from a function. But we can
either use pointers to static or heap memory locations to return multiple values or we
can put data in the structure and then return the structure.

To know more about it, refer to this article – How to return multiple values from a
function in C or C++?

Q6. What is the actual and formal parameter?

Answer:
Formal parameter: The variables declared in the function prototype is known as
Formal arguments or parameters.

Actual parameter: The values that are passed in the function are known as actual
arguments or parameters.

User-Defined Function in C
A user-defined function is a type of function in C language that is defined by the user himself to
perform some specific task. It provides code reusability and modularity to our program. User-
defined functions are different from built-in functions as their working is specified by the user and
no header file is required for their usage.

In this article, we will learn about user-defined function, function prototype, function definition,
function call, and different ways in which we can pass parameters to a function.

How to use User-Defined Functions in C?


To use a user-defined function, we first have to understand the different parts of its syntax. The
user-defined function in C can be divided into three parts:

1. Function Prototype
2. Function Definition
3. Function Call

C Function Prototype
A function prototype is also known as a function declaration which specifies the function’s name,
function parameters, and return type. The function prototype does not contain the body of the
function. It is basically used to inform the compiler about the existence of the user-defined function
which can be used in the later part of the program.

Syntax

return_type function_name (type1 arg1 , type2 arg2, ... typeN argN );

We can also skip the name of the arguments in the function prototype. So,

return_type function_name (type1 , type2 , ... typeN);


C Function Definition
Once the function has been called, the function definition contains the actual statements that will be
executed. All the statements of the function definition are enclosed within { } braces.

Syntax

return_type function_name (type1 arg1, type2 arg2 .... typeN argN) {

// actual statements to be executed // return value if any

}
Note: If the function call is present after the function definition, we can skip the
function prototype part and directly define the function.

C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called using
their names followed by round brackets. Their arguments are passed inside the brackets.

Syntax

function_name(arg1, arg2, ... argN);

Example of User-Defined Function


The following C program illustrates how to use user-defined functions in our program.

// C Program to illustrate the use of user-


defined function
#include <stdio.h>

// Function prototype
int sum(int, int);

// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}

// Driver code
int main()
{
int x = 10, y = 11;

// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y,
result);

return 0;
}
Output
Sum of 10 and 11 = 21

Components of Function Definition


There are three components of the function definition:

1. Function Parameters
2. Function Body
3. Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called
function by the caller. We can pass none or any number of function parameters to the function.

We have to define the function name and its type in the function definition and we can only pass
the same number and type of parameters in the function call.

Example

int foo (int a, int b);

Here, a and b are function parameters.

Note: C language provides a method using which we can pass variable number of
arguments to the function. Such functions are called variadic function.

2. Function Body

The function body is the set of statements that are enclosed within { } braces. They are the
statements that are executed when the function is called.

Example

int foo (int a, int b) {


int sum = a + b; return sum;

}
Here, the statements between { and } is function body.

3. Return Value

The return value is the value returned by the function to its caller. A function can only return a
single value and it is optional. If no value is to be returned, the return type is defined as void.

The return keyword is used to return the value from a function.

Syntax

return (expression);
Example

int foo (int a, int b) {


return a + b;

}
Note: We can use pointers or structures to return multiple values from a function in C.

Passing Parameters to User-Defined Functions


We can pass parameters to a function in C using two methods:

1. Call by Value
2. Call by Reference

1. Call by value

In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in different
memory locations.

Example

// C program to show use of


// call by value
#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap
are: %d, %d\n", x,
y);
swap(x, y);
printf("Values of x and y after swap
are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
Note: Values aren’t changed in the call by value since they aren’t passed by reference.

2. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes that are
made to the function are reflected back to the values. We use the pointers of the required type to
receive the address in the function.

Example

// C program to implement
// Call by Reference
#include <stdio.h>

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}

// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap
are: %d, %d\n", x,
y);
swap(&x, &y);
printf("Values of x and y after swap
are: %d, %d", x,
y);
return 0;
}

Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 20, 10
For more details, refer to this article – Difference between Call by Value and Call by Reference

Advantages of User-Defined Functions


The advantages of using functions in the program are as follows:

 One can avoid duplication of code in the programs by using functions. Code can be written
more quickly and be more readable as a result.
 Code can be divided and conquered using functions. This process is known as Divide and
Conquer. It is difficult to write large amounts of code within the main function, as well as testing
and debugging. Our one task can be divided into several smaller sub-tasks by using functions,
thus reducing the overall complexity.
 For example, when using pow, sqrt, etc. in C without knowing how it is implemented, one
can hide implementation details with functions.
 With little to no modifications, functions developed in one program can be used in another,
reducing the development time.
Parameter Passing Techniques in C/C++
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case, A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.

Terminology

 Formal Parameter: A variable and its type as they appear in the prototype of the function or
method.
 Actual Parameter: The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
 Modes:
 IN: Passes info from caller to the callee.
 OUT: Callee writes values in the caller.
 IN/OUT: The caller tells the callee the value of the variable, which may be updated by
the callee.
Important Methods of Parameter Passing are as follows:

1. Pass By Value
This method uses in-mode semantics. Changes made to formal parameters do not get transmitted
back to the caller. Any modifications to the formal parameter variable inside the called function or
method affect only the separate storage location and will not be reflected in the actual parameter
in the calling environment. This method is also called call by value.

Example of Pass by Value

// C program to illustrate
// call by value
#include <stdio.h>
void func(int a, int b)
{
a += b;
printf("In func, a = %d b
= %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;

// Passing parameters
func(x, y);
printf("In main, x = %d y
= %d\n", x, y);
return 0;
}

Output
In func, a = 12 b = 7
In main, x = 5 y = 7
Note: Languages like C, C++, and Java support this type of parameter passing. Java in
fact is strictly call by value.

Shortcomings of Pass By Value:

 Inefficiency in storage allocation


 For objects and arrays, the copy semantics are costly

2. Pass by reference(aliasing)
This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted
back to the caller through parameter passing. Any changes to the formal parameter are reflected in
the actual parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as call by reference. This method is efficient in
both time and space.

Example
// C program to illustrate
// call by reference
#include <stdio.h>

void swapnum(int* i, int* j)


{
int temp = *i;
*i = *j;
*j = temp;
}

int main(void)
{
int a = 10, b = 20;

// passing parameters
swapnum(&a, &b);

printf("a is %d and b
is %d\n", a, b);
return 0;
}

Output
a is 20 and b is 10
Note: C and C++ both support call by value as well as call by reference whereas Java
doesn’t support call by reference.

Shortcomings of Pass by Reference

 Many potential scenarios can occur


 Programs are difficult to understand sometimes

Other Methods of Parameter Passing


These techniques are older and were used in earlier programming languages like Pascal, Algol, and
Fortran. These techniques are not applicable in high-level languages.

1. Pass by Result

This method uses out-mode semantics. Just before control is transferred back to the caller, the
value of the formal parameter is transmitted back to the actual parameter. This method is
sometimes called call by the result. In general, the pass-by-result technique is implemented by
copying.

2. Pass by Value-Result

This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-Result.


Just before the control is transferred back to the caller, the value of the formal parameter is
transmitted back to the actual parameter. This method is sometimes called call by value-result.

3. Pass by Name
This technique is used in programming languages such as Algol. In this technique, the symbolic
“name” of a variable is passed, which allows it both to be accessed and updated.

Example

To double the value of C[j], you can pass its name (not its value) into the following procedure.

procedure double(x);
real x;
begin
x:=x*2
end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for
the corresponding parameter in the body of the procedure. Implications of Pass-by-Name
mechanism:

 The argument expression is re-evaluated each time the formal parameter is passed.
 The procedure can change the values of variables used in the argument expression and hence
change the expression’s value.
If you like GeeksforGeeks and would like to contribute, you can also write an article
using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your
article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.

Function Prototype in C
The C function prototype is a statement that tells the compiler about the function’s name, its
return type, numbers and data types of its parameters. By using this information, the compiler
cross-checks function parameters and their data type with function definition and function call.

Function prototype works like a function declaration where it is necessary where the function
reference or call is present before the function definition but optional if the function definition is
present before the function call in the program.

Syntax
return_type function_name(parameter_list);

where,

 return_type: It is the data type of the value that the function returns. It can be any data
type int, float, void, etc. If the function does not return anything, void is used as the return type.
 function_name: It is the identifier of the function. Use appropriate names for the functions
that specify the purpose of the function.
 parameter_list: It is the list of parameters that a function expects in parentheses. A
parameter consists of its data type and name. If we don’t want to pass any parameter, we can
leave the parentheses empty.
For example,
int func(int, char, char *, float);

Example:
Program to illustrate the Function Prototype

// C program to illustrate the function


prototye
#include <stdio.h>

// Function prototype
float calculateRectangleArea(float length,
float width);

int main()
{
float length = 5.0;
float width = 3.0;

// Function call
float area = calculateRectangleArea(length,
width);

printf("The area of the rectangle


is: %.2f\n", area);

return 0;
}

// Function definition
float calculateRectangleArea(float length,
float width)
{
return length * width;
}

Output
The area of the rectangle is: 15.00

What if the function prototype is not specified?


If we ignore the function prototype, a program may compile with a warning, it may give errors and
may work properly. But sometimes, it will give strange output and it is very hard to find such
programming mistakes.

Example: Program without a function prototype

The below code opens a file specified by the command-line argument, checks if the file exists, and
then closes the file. The prototype of strerror function is not included in the code.

// C code to check if a file exists or not.


// Prototype of strerror function is not
included in the
// code.
#include <errno.h>
#include <stdio.h>

int main(int argc, char* argv[])


{
FILE* fp;

fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "%s\n",
strerror(errno));
return errno;
}

printf("file exist\n");

fclose(fp);

return 0;
}

Let us provide a filename, which does not exist in a file system, and check the output of the
program on x86_64 architecture.

Output
[narendra@/media/partition/GFG]$ ./file_existence hello.c
Segmentation fault (core dumped)

Explanation

The above program checks the existence of a file, provided from the command line, if a given file
exists, then the program prints “file exists”, otherwise it prints an appropriate error message.

Why did this program crash, instead it should show an appropriate error message. This program
will work fine on x86 architecture but will crash on x86_64 architecture. Let us see what was
wrong with the code. Carefully go through the program, deliberately I haven’t included
the prototype of the “strerror()” function. This function returns a “pointer to the character”, which
will print an error message which depends on the errno passed to this function.

Note that x86 architecture is an ILP-32 model, which means integers, pointers, and long are 32-
bit wide, that’s why the program will work correctly on this architecture. But x86_64 is the LP-64
model, which means long and pointers are 64-bit wide. In C language, when we don’t provide a
prototype of a function, the compiler assumes that the function returns an integer . In our example,
we haven’t included the “string.h” header file (strerror’s prototype is declared in this file), that’s
why the compiler assumed that the function returns an integer. But its return type is a pointer to a
character.

In x86_64, pointers are 64-bit wide and integers are 32-bit wide, that’s why while returning from
a function, the returned address gets truncated (i.e. 32-bit wide address, which is the size of
integer on x86_64) which is invalid and when we try to dereference this address, the result is
a segmentation fault.

Now include the “string.h” header file and check the output, the program will work correctly and
gives the following output.
[narendra@/media/partition/GFG]$ ./file_existence hello.c
No such file or directory

Consider one more example

This code demonstrates the process of dynamic memory allocation using the malloc function, but
the prototype of the malloc function is not included.

// This code dynamically allocates memory for


an integer
// using the malloc function but prototype of
malloc
// function is not included in the code

#include <stdio.h>

int main(void)
{
int* p = malloc(sizeof(int));

if (p == NULL) {
perror("malloc()");
return -1;
}

*p = 10;
free(p);

return 0;
}

Explanation

The above code will work fine on the IA-32 model but will fail on the IA-64 model. The reason for
the failure of this code is we haven’t included a prototype of the malloc() function and the returned
value is truncated in the IA-64 model.

FAQs on Function Prototype

Q1. Difference between Function Declaration and Function Prototype

Answer:

Following are some differences between Function and Function Prototype:

Function Declaration Function Prototype

The function prototype tells the


Function Declaration is used to tell the
compiler about the existence and
existence of a function.
signature of the function.

A function declaration is valid even with A function prototype is a function


only function name and return delcaration that provides the
type. function’s name, return type, and
Function Declaration Function Prototype

parameter list without including the


function body.

Typically used in header files to declare Used to declare functions before their
functions. actual definitions.

Syntax: Syntax:
return_type function_name(); return_type function_name(parameter_list);

How can I return multiple values from a function?


We all know that a function in C can return only one value. So how do we achieve the purpose of
returning multiple values.
Well, first take a look at the declaration of a function.

int foo(int arg1, int


arg2);

So we can notice here that our interface to the function is through arguments and return value only.
(Unless we talk about modifying the globals inside the function)

Let us take a deeper look…Even though a function can return only one value but that value can be
of pointer type. That’s correct, now you’re speculating right!
We can declare the function such that, it returns a structure type user defined variable or a pointer
to it . And by the property of a structure, we know that a structure in C can hold multiple values
of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on…)

If we want the function to return multiple values of same data types, we could return the pointer
to array of that data types.

We can also make the function return multiple values by using the arguments of the function. How?
By providing the pointers as arguments.

Usually, when a function needs to return several values, we use one pointer in return instead of
several pointers as arguments.

Please see How to return multiple values from a function in C or C++? for more details.
main Function in C
The main function is an integral part of the programming languages such as C, C++, and Java.
The main function in C is the entry point of a program where the execution of a program starts. It
is a user-defined function that is mandatory for the execution of a program because when a C
program is executed, the operating system starts executing the statements in the main() function.

Syntax of C main() Function


return_type main() {
// Statement 1; // Statement 2; // and so on..

return;
}
We can write the main function in many ways in C language as follows:

int main(){} or int main(void){}


main(){} or void main(){} or main(void){} or void main(void){}
In the above notations, int means integer return type, and void return type means that does not
return any information, or (void) or () means that does not take any information.

Important Points about C main Function


 It is the function where the program’s execution starts.
 Every program has exactly one main function.
 The name of this function should be “main” not anything else.
 The main function always returns an integer value or void.
 The main function is called by OS, not the user.

Types of C main Functions


1. Main function with no arguments and void return type
2. Main function with no arguments and int return type
3. Main function with the Command Line Arguments

1. Main Function with No Arguments and Void Return Type

Let’s see the example of the main function inside which we have written a simple program for
printing a string. In the below code, first, we include a header file and then we define a main
function inside which we write a statement to print a string using printf() function. The main
function is called by the operating system itself and then executes all statements inside this function.

Syntax

void main()
{
// Function body
}
The above function is equivalent to:

void main (void)


{
// Function Body
}
Example

// C Program to show main with no return


type and no
// arguments
#include <stdio.h>

// Defining a main function


void main()
{

// code
printf("Hello Geek!");
}

Output
Hello Geek!
Note: The return type of main function according to C standard should be int only.
Even if your compiler is able to run void main(), it is recommended to avoid it.

2. Main Function with No Arguments and int Return Type

In this example, we use the int return type in the main() function that indicates the exit status of
the program. The exit status is a way for the program to communicate to the operating system
whether the program was executed successfully or not. The convention is that a return value of 0
indicates that the program was completed successfully, while any other value indicates that an error
occurred.

Syntax

int main()
{
// Function body
}
or

int main(void)
{
// Function Body
}
Example

// C Program to show the main function with int


return type
// and no arguments
#include <stdio.h>

int main()
{
printf("Hello Geek!");
return 0;
}

Output
Hello Geek!

3. Main Function with the Command Line Arguments

In this example, we have passed some arguments in the main() function as seen in the below code.
These arguments are called command line arguments and these are given at the time of executing a
program.

The first argument argc means argument count which means it stores the number of arguments
passed in the command line and by default, its value is 1 when no argument is passed.

The second argument is a char pointer array argv[] which stores all the command line arguments
passed. We can also see in the output when we run the program without passing any command line
argument the value of argc is 1.

Syntax

int main(int argc, char* argv[])


{
// Function body
}
Example

// C Program to illustrate the main function with command


line arguments
#include <stdio.h>

int main(int argc, char* argv)


{

// printing the coundt of arguments


printf("The value of argc is %d\n", argc);
// prining each argument
for (int i = 0; i < argc; i++) {
printf("%s \n", argv[i]);
}

return 0;
}

Output
The value of argc is 1
./369df037-e886-4cfb-9fd4-ad6a358ad7c6
Now, run the programs in the command prompt or terminal as seen below screenshot and passed
any arguments. main.exe is the name of the executable file created when the program runs for the
first time. We passed three arguments “geeks for geeks” and print them using a loop.

Output of Main with Command Line Arguments

Implicit return type int in C


Predict the output of following C program.

#include <stdio.h>
fun(int x)
{
return x*x;
}
int main(void)
{
printf("%d",
fun(10));
return 0;
}

Output: 100

The important thing to note is, there is no return type for fun(), the program still compiles and
runs fine in most of the C compilers. In C, if we do not specify a return type, compiler assumes an
implicit return type as int. However, C99 standard doesn’t allow return type to be omitted even if
return type is int. This was allowed in older C standard C89.

In C++, the above program is not valid except few old C++ compilers like Turbo C++. Every function
should specify the return type in C++.

Please write comments if you find anything incorrect, or you want to share more information about
the topic discussed above

Callbacks in C
A callback is any executable code that is passed as an argument to another code, which is expected
to call back (execute) the argument at a given time. In simple language, If a reference of a function
is passed to another function as an argument to call it, then it will be called a Callback function.

In C, a callback function is a function that is called through a function pointer.

Below is a simple example in C to illustrate the above definition to make it more clear.
// A simple C program to demonstrate
callback
#include <stdio.h>

void A(){
printf("I am function A\n");
}

// callback function
void B(void (*ptr)())
{
(*ptr)(); // callback to A
}

int main()
{
void (*ptr)() = &A;

// calling function B and passing


// address of the function A as
argument
B(ptr);

return 0;
}

Output
I am function A
In C++ STL, functors are also used for this purpose.

If you like GeeksforGeeks and would like to contribute, you can also write an article
using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.

Nested functions in C
Some programmer thinks that defining a function inside an another function is known as “nested
function”. But the reality is that it is not a nested function, it is treated as lexical scoping. Lexical
scoping is not valid in C because the compiler cant reach/find the correct memory location of the
inner function.

Nested function is not supported by C because we cannot define a function within another function
in C. We can declare a function inside a function, but it’s not a nested function.
Because nested functions definitions can not access local variables of the surrounding blocks, they
can access only global variables of the containing module. This is done so that lookup of global
variables doesn’t have to go through the directory. As in C, there are two nested scopes: local and
global (and beyond this, built-ins). Therefore, nested functions have only a limited use. If we try to
approach nested function in C, then we will get compile time error.

// C program to illustrate the


// concept of Nested function.
#include <stdio.h>
int main(void)
{
printf("Main");
int fun()
{
printf("fun");

// defining view() function inside fun()


function.
int view()
{
printf("view");
}
return 1;
}
view();
}

Output:

Compile time error: undefined reference to `view'


An extension of the GNU C Compiler allows the declarations of nested functions. The declarations of
nested functions under GCC’s extension need to be prefix/start with the auto keyword.

// C program of nested function


// with the help of gcc extension
#include <stdio.h>
int main(void)
{
auto int view(); // declare function with
auto keyword
view(); // calling function
printf("Main\n");

int view()
{
printf("View\n");
return 1;
}

printf("GEEKS");
return 0;
}

Output:

view
Main
GEEKS
If you like GeeksforGeeks and would like to contribute, you can also write an article
using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.

Variadic functions in C
Variadic functions are functions that can take a variable number of arguments. In C programming, a
variadic function adds flexibility to the program. It takes one fixed argument and then any number of
arguments can be passed. The variadic function consists of at least one fixed variable and then an
ellipsis(…) as the last parameter.

Syntax:

int function_name(data_type variable_name, ...);


Values of the passed arguments can be accessed through the header file named as:

#include <stdarg.h>
<stdarg.h> includes the following methods:

Methods Description

This enables access to variadic function arguments.


where *va_list* will be the pointer to the last fixed argument in the
variadic function
*argN* is the last fixed argument in the variadic function.
va_start(va_list ap, argN)
From the above variadic function (function_name (data_type
variable_name, …);), variable_name is the last fixed argument
making it the argN. Whereas *va_list ap* will be a pointer to argN
(variable_name)

This one accesses the next variadic function argument.


*va_list ap* is the same as above i.e a pointer to argN
va_arg(va_list ap, type)
*type* indicates the data type the *va_list ap* should expect
(double, float, int etc.)

va_copy(va_list dest,
This makes a copy of the variadic function arguments.
va_list src)

This ends the traversal of the variadic function


va_end(va_list ap)
arguments.

Here, va_list holds the information needed by va_start, va_arg, va_end, and va_copy.

Program 1:

The following simple C program will demonstrate the working of the variadic function AddNumbers():
// C program for the above
approach

#include <stdarg.h>
#include <stdio.h>

// Variadic function to add


numbers
int AddNumbers(int n, ...)
{
int Sum = 0;

// Declaring pointer to the


// argument list
va_list ptr;

// Initializing argument to
the
// list pointer
va_start(ptr, n);

for (int i = 0; i < n; i++)

// Accessing current
variable
// and pointing to next
one
Sum += va_arg(ptr, int);

// Ending argument list


traversal
va_end(ptr);

return Sum;
}

// Driver Code
int main()
{
printf("\n\n Variadic
functions: \n");

// Variable number of
arguments
printf("\n 1 + 2 = %d ",
AddNumbers(2, 1, 2));

printf("\n 3 + 4 + 5 = %d ",
AddNumbers(3, 3, 4,
5));

printf("\n 6 + 7 + 8 + 9 = %d
",
AddNumbers(4, 6, 7, 8,
9));

printf("\n");
return 0;
}

Output:

Variadic functions:

1 + 2 = 3
3 + 4 + 5 = 12
6 + 7 + 8 + 9 = 30

Program 2: Below is the C program consisting of the variadic function LargestNumber():

// C program for the above approach


#include <stdarg.h>
#include <stdio.h>

// Variadic function to find the


largest number
int LargestNumber(int n, ...)
{
// Declaring pointer to the
// argument list
va_list ptr;

// Initializing argument to the


// list pointer
va_start(ptr, n);

int max = va_arg(ptr, int);

for (int i = 0; i < n-1; i++) {

// Accessing current variable


// and pointing to next
int temp = va_arg(ptr, int);
max = temp > max ? temp : max;
}

// End of argument list traversal


va_end(ptr);

return max;
}

// Driver Code
int main()
{
printf("\n\n Variadic functions:
\n");

// Variable number of arguments


printf("\n %d ",
LargestNumber(2, 1, 2));
printf("\n %d ",
LargestNumber(3, 3, 4, 5));

printf("\n %d ",
LargestNumber(4, 6, 7, 8,
9));

printf("\n");

return 0;
}

Output:

Variadic functions:

2
5
9

_Noreturn function specifier in C


The _Noreturn keyword appears in a function declaration and specifies that the function does not
return by executing the return statement or by reaching the end of the function body. If the
function declared _Noreturn returns, the behavior is undefined. A compiler diagnostic is
recommended if this can be detected.

The _Noreturn specifier may appear more than once in the same function declaration, the behavior
is the same as if it appeared once.

This specifier is typically used through the convenience macro noreturn, which is provided in the
header stdnoreturn.h.

Note:

function specifier is deprecated. [[noreturn]] attribute should be


_Noreturn
used instead.
The macro noreturn is also deprecated.
Example:

// C program to show how _Noreturn


type
// function behave if it has return
statement.
#include <stdio.h>
#include <stdlib.h>

// With return value


_Noreturn void view()
{
return 10;
}
int main(void)
{
printf("Ready to begin...\n");
view();

printf("NOT over till now\n");


return 0;
}

Output:

Ready to begin...
After that abnormal termination of program.
compiler error:[Warning] function declared 'noreturn' has a 'return' statement

// C program to illustrate the


working
// of _Noreturn type function.
#include <stdio.h>
#include <stdlib.h>

// Nothing to return
_Noreturn void show()
{
printf("BYE BYE");
}
int main(void)
{
printf("Ready to
begin...\n");
show();

printf("NOT over till


now\n");
return 0;
}

Output:

Ready to begin...
BYE BYE

Predefined Identifier __func__ in C


Before we start discussing __func__, let us write some code snippets and anticipate the output:

// C program to demonstrate working of a


// Predefined Identifier __func__

#include <stdio.h>

int main()
{
// %s indicates that the program will
read strings
printf("%s", __func__);
return 0;
}

Output
main
C language standard (i.e. C99 and C11) defines a predefined identifier as follows in clause 6.4.2.2:

“The identifier __func__ shall be implicitly declared by the translator as if, immediately
following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";


appeared, where function-name is the name of the lexically-enclosing function.”

It means that the C compiler implicitly adds __func__ in every function so that it can be used in that
function to get the function name.

Example:

// C program to demonstrate
__func__
#include <stdio.h>

// %s is used to read strings


void foo(void) { printf("%s",
__func__); }
void bar(void) { printf("%s",
__func__); }

int main()
{
foo();
bar();
return 0;
}

Output
foobar
A use case of this predefined identifier could be logging the output of a big program where a
programmer can use __func__ to get the current function instead of mentioning the complete
function name explicitly.

Now, what happens if we define one more variable of name __func__?

Example:

// C program to demonstrate
double
// predefined identifier or
__func__
#include <stdio.h>

int __func__ = 10;


int main()
{
printf("%s", __func__);
return 0;
}

Expected Error in Predefined Identifier

Since the C standard says the compiler implicitly defines __func__ for each function as the function
name, we should not define __func__ in the first place. You might get an error but the C standard
says “undefined behavior” if someone explicitly defines __func__.

Just to finish the discussion on Predefined Identifier __func__, let us mention Predefined Macros as
well (such as __FILE__ and __LINE__, etc.) Basically, C standard clause 6.10.8 mentions several
predefined macros out of which __FILE__ and __LINE__ are of relevance here.

It’s worthwhile to see the output of the following code snippet:

// C program to demonstrate __FILE__,


func, line
#include <stdio.h>

int main()
{
printf("In file:%s, function:%s() and
line:%d",
__FILE__, __func__, __LINE__);

return 0;
}

Instead of explaining the output, we will leave this to you to guess and understand the role
of __FILE__ and __LINE__ !

C Library math.h Functions


The math.h header defines various C mathematical functions and one macro. All the functions
available in this library take double as an argument and return double as the result. Let us discuss
some important C math functions one by one.
C Math Functions

1. double ceil (double x)

The C library function double ceil (double x) returns the smallest integer value greater than or equal
to x.

Syntax
double ceil(double x);
Example

// C code to illustrate
// the use of ceil function.
#include <math.h>
#include <stdio.h>

int main()
{
float val1, val2, val3, val4;

val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;

printf("value1 = %.1lf\n",
ceil(val1));
printf("value2 = %.1lf\n",
ceil(val2));
printf("value3 = %.1lf\n",
ceil(val3));
printf("value4 = %.1lf\n",
ceil(val4));

return (0);
}

Output
value1 = 2.0
value2 = 2.0
value3 = -2.0
value4 = -2.0

2. double floor(double x)

The C library function double floor(double x) returns the largest integer value less than or equal to x.

Syntax
double floor(double x);
Example

// C code to illustrate
// the use of floor function
#include <math.h>
#include <stdio.h>

int main()
{
float val1, val2, val3, val4;

val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;

printf("Value1 = %.1lf\n",
floor(val1));
printf("Value2 = %.1lf\n",
floor(val2));
printf("Value3 = %.1lf\n",
floor(val3));
printf("Value4 = %.1lf\n",
floor(val4));

return (0);
}

Output
Value1 = 1.0
Value2 = 1.0
Value3 = -3.0
Value4 = -3.0

3. double fabs(double x)

The C library function double fabs(double x) returns the absolute value of x.

Syntax
syntax : double fabs(double x)
Example

// C code to illustrate
// the use of fabs function
#include <math.h>
#include <stdio.h>

int main()
{
int a, b;
a = 1234;
b = -344;

printf("The absolute value of %d is %lf\n", a,


fabs(a));
printf("The absolute value of %d is %lf\n", b,
fabs(b));

return (0);
}

Output
The absolute value of 1234 is 1234.000000
The absolute value of -344 is 344.000000

4. double log(double x)

The C library function double log(double x) returns the natural logarithm (base-e logarithm) of x.

Syntax
double log(double x)
Example

// C code to illustrate
// the use of log function

#include <math.h>
#include <stdio.h>

int main()
{
double x, ret;
x = 2.7;

/* finding log(2.7) */
ret = log(x);
printf("log(%lf) = %lf", x,
ret);

return (0);
}

Output
log(2.700000) = 0.993252

5. double log10(double x)

The C library function double log10(double x) returns the common logarithm (base-10 logarithm) of
x.

Syntax
double log10(double x);
Example

// C code to illustrate
// the use of log10 function
#include <math.h>
#include <stdio.h>

int main()
{
double x, ret;
x = 10000;
/* finding value of log1010000
*/
ret = log10(x);
printf("log10(%lf) = %lf\n",
x, ret);

return (0);
}

Output
log10(10000.000000) = 4.000000

6. double fmod(double x, double y)

The C library function double fmod(double x, double y) returns the remainder of x divided by y.

Syntax
double fmod(double x, double y)
Example

// C code to illustrate
// the use of fmod function
#include <math.h>
#include <stdio.h>

int main()
{
float a, b;
int c;
a = 8.2;
b = 5.7;
c = 3;
printf("Remainder of %f / %d
is %lf\n", a, c,
fmod(a, c));
printf("Remainder of %f / %f
is %lf\n", a, b,
fmod(a, b));

return (0);
}

Output

Remainder of 8.200000 / 3 is 2.200000


Remainder of 8.200000 / 5.700000 is 2.500000

7. double sqrt(double x)

The C library function double sqrt(double x) returns the square root of x.

Syntax
double sqrt(double x);
Example
// C code to illustrate
// the use of sqrt function
#include <math.h>
#include <stdio.h>

int main()
{

printf("Square root of %lf


is %lf\n", 225.0,
sqrt(225.0));
printf("Square root of %lf
is %lf\n", 300.0,
sqrt(300.0));

return (0);
}

Output
Square root of 225.000000 is 15.000000
Square root of 300.000000 is 17.320508

8. double pow(double x, double y)

The C library function double pow(double x, double y) returns x raised to the power of y i.e. xy.

Syntax
double pow(double x, double y);
Example

// C code to illustrate
// the use of pow function
#include <math.h>
#include <stdio.h>

int main()
{
printf("Value 8.0 ^ 3 = %lf\n", pow(8.0,
3));

printf("Value 3.05 ^ 1.98 = %lf",


pow(3.05, 1.98));

return (0);
}

Output
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324

9. double modf(double x, double *integer)

The C library function double modf(double x, double *integer) returns the fraction component (part
after the decimal), and sets integer to the integer component.
Syntax
double modf(double x, double *integer)
Example

// C code to illustrate
// the use of modf function
#include <math.h>
#include <stdio.h>

int main()
{
double x, fractpart, intpart;

x = 8.123456;
fractpart = modf(x, &intpart);

printf("Integral part = %lf\n",


intpart);
printf("Fraction Part = %lf \n",
fractpart);

return (0);
}

Output
Integral part = 8.000000
Fraction Part = 0.123456

10. double exp(double x)

The C library function double exp(double x) returns the value of e raised to the xth power.

Syntax
double exp(double x);
Example

// C code to illustrate
// the use of exp function
#include <math.h>
#include <stdio.h>

int main()
{
double x = 0;

printf("The exponential value of %lf


is %lf\n", x,
exp(x));
printf("The exponential value of %lf
is %lf\n", x + 1,
exp(x + 1));
printf("The exponential value of %lf
is %lf\n", x + 2,
exp(x + 2));

return (0);
}

Output
The exponential value of 0.000000 is 1.000000
The exponential value of 1.000000 is 2.718282
The exponential value of 2.000000 is 7.389056

11. double cos(double x)

The C library function double cos(double x) returns the cosine of a radian angle x.

Syntax
double cos(double x);
The same syntax can be used for other trigonometric functions like sin, tan, etc.

Example

// C code to illustrate
// the use of cos function
#include <math.h>
#include <stdio.h>

#define PI 3.14159265

int main()
{
double x, ret, val;

x = 60.0;
val = PI / 180.0;
ret = cos(x * val);
printf("The cosine of %lf is %lf
degrees\n", x, ret);

x = 90.0;
val = PI / 180.0;
ret = cos(x * val);
printf("The cosine of %lf is %lf
degrees\n", x, ret);

return (0);
}

Output
The cosine of 60.000000 is 0.500000 degrees
The cosine of 90.000000 is 0.000000 degrees

12. double acos(double x)

The C library function double acos(double x) returns the arc cosine of x in radians.

Syntax
double acos(double x);
The same syntax can be used for other arc trigonometric functions like asin, atan etc.
Example

// C code to illustrate
// the use of acos function
#include <math.h>
#include <stdio.h>

#define PI 3.14159265

int main()
{
double x, ret, val;

x = 0.9;
val = 180.0 / PI;

ret = acos(x) * val;


printf("The arc cosine of %lf is %lf
degrees", x, ret);

return (0);
}

Output
The arc cosine of 0.900000 is 25.841933 degrees

13. double tanh(double x)

The C library function double tanh(double x) returns the hyperbolic tangent of x.

Syntax
double tanh(double x);
The same syntax can be used for other hyperbolic trigonometric functions like sinh, cosh etc.

Example
C Functions
// C code to illustrate
// the use of tanh function
#include <math.h>  C Functions
#include <stdio.h>  User-Defined Function in C
 Parameter Passing Techniques in C
int main()
{  Importance of Function Prototype in C
double x, ret;  Return Multiple Values From a Function
x = 0.5;  main Function in C

ret = tanh(x);  Implicit Return Type int in C


printf("The hyperbolic tangent of %lf is %lf  Callbacks in C
degrees",  Nested Functions in C
x, ret);
 Variadic functions in C
return (0);  _Noreturn Function Specifier in C
}  Predefined Identifier __func__ in C
 Maths Functions in C
Output
The hyperbolic tangent of 0.500000 is 0.462117 degrees

You might also like