C Functions
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
The parameter name is not mandatory while declaring functions. We can also declare the function
without using the name of the data variables.
Example
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.
{
// 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>
// Driver code
int main()
{
// Calling sum function and
// storing its value in add
variable
int add = sum(10, 30);
Output
Sum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and called the
function.
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);
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:
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double Number;
Number = 49;
Output
The Square root of 49.00 = 7.00
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.
// C program to show
// user-defined
functions
#include <stdio.h>
// Driver code
int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b);
Output
Sum is: 70
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:
// 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:
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:
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
Answer:
Functions are the block of code that is executed every time they are called during an
execution of a program.
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.
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.
Answer:
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.
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++?
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.
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
We can also skip the name of the arguments in the function prototype. So,
Syntax
}
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 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
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
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
}
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.
Syntax
return (expression);
Example
}
Note: We can use pointers or structures to return multiple values from a function in C.
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
// 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>
// 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
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.
// 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.
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>
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.
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
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 [email protected]. 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
// 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);
return 0;
}
// Function definition
float calculateRectangleArea(float length,
float width)
{
return length * width;
}
Output
The area of the rectangle is: 15.00
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.
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
This code demonstrates the process of dynamic memory allocation using the malloc function, but
the prototype of the malloc function is not included.
#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.
Answer:
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);
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.
return;
}
We can write the main function in many ways in C language as follows:
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:
// 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.
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
int main()
{
printf("Hello Geek!");
return 0;
}
Output
Hello Geek!
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
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.
#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.
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;
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 [email protected]. 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.
Output:
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 [email protected]. 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:
#include <stdarg.h>
<stdarg.h> includes the following methods:
Methods Description
va_copy(va_list dest,
This makes a copy of the variadic function arguments.
va_list src)
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>
// Initializing argument to
the
// list pointer
va_start(ptr, n);
// Accessing current
variable
// and pointing to next
one
Sum += va_arg(ptr, int);
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
return max;
}
// Driver Code
int main()
{
printf("\n\n Variadic functions:
\n");
printf("\n %d ",
LargestNumber(4, 6, 7, 8,
9));
printf("\n");
return 0;
}
Output:
Variadic functions:
2
5
9
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:
Output:
Ready to begin...
After that abnormal termination of program.
compiler error:[Warning] function declared 'noreturn' has a 'return' statement
// Nothing to return
_Noreturn void show()
{
printf("BYE BYE");
}
int main(void)
{
printf("Ready to
begin...\n");
show();
Output:
Ready to begin...
BYE BYE
#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
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>
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.
Example:
// C program to demonstrate
double
// predefined identifier or
__func__
#include <stdio.h>
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.
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__ !
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)
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;
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
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
7. double sqrt(double x)
Syntax
double sqrt(double x);
Example
// C code to illustrate
// the use of sqrt function
#include <math.h>
#include <stdio.h>
int main()
{
return (0);
}
Output
Square root of 225.000000 is 15.000000
Square root of 300.000000 is 17.320508
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));
return (0);
}
Output
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324
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);
return (0);
}
Output
Integral part = 8.000000
Fraction Part = 0.123456
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;
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
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
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;
return (0);
}
Output
The arc cosine of 0.900000 is 25.841933 degrees
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