C 4th Unit
C 4th Unit
The form of C functions, Return values and types, calling a function, categories of
functions, Nested functions, Recursion, functions with arrays, call by value, call by
reference, storage classes-character arrays and string functions
Function
A function 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.
Syntax of Function
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); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
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.
Return values and types
Return values
A function may or may not send any value to the calling function. If it does, it is done
through the return statement. While it is possible to pass to the called function any number of values,
the called function can only return one value per call, at the most.
This function value can then be used in any assignment or expression as in:
#include <stdio.h>
test()
if(1==1)
return 10;
void main() {
int capturedValue=test();
Output
Return Types
The int before the function definitions of getint and difference could be omitted as the
default function type is int, however it improves the program readability to specify the return
type explicitly.
If a function returns a type other than int the type must be declared in the function definition.
Calling a function
To execute a function, it should be called with a 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.
Output
Sum is: 40
Categories of Function
There are four Categories of functions divided on the basis of arguments they accept
and the value they return:
Syntax
void function_name()
// no return value
return;
Example
#include <stdio.h>
void sum()
int x, y;
// Driver code
void main()
// function call
sum();
}
Function with No Arguments and With Return Value
Functions that have no arguments but have some return values. Such functions are
used to perform specific operations and return their value.
Syntax
return_type function_name()
// program
return value;
Example
#include <stdio.h>
int sum()
int x, y, s = 0;
s = x + y;
return s;
int main()
return 0;
}
Function With Arguments and No Return Value
Functions that have arguments but no return values. Such functions are used to display or
perform some operations on given arguments.
Syntax
// Program
return;
Example
#include <stdio.h>
int main()
int x, y;
// function call
sum(x, y);
return 0;
}
Function With Arguments and With Return Value
Functions that have arguments and some return value. These functions are used to perform
specific operations on the given arguments and return their values to the user.
Syntax
// program
return value;
Example
#include <stdio.h>
return x + y;
int main()
int x, y;
// function call
return 0;
}
Nested functions
Nested functions in C refer to the ability to define functions within the scope of other
functions. Unlike many other programming languages, C traditionally doesn't support nested
functions. However, some compilers, such as GNU Compiler Collection (GCC), offer an
extension to the C language that enables nested functions.
With nested functions, you can declare a function inside another function's body. The nested
function has access to all variables in the enclosing function's scope, including local
variables and parameters. This feature allows for more modular and readable code by
encapsulating related functionality within the context where it's needed.
Example
#include <stdio.h>
void outerFunction() {
int x = 10;
void innerFunction() {
innerFunction();
int main() {
outerFunction();
return 0;
Output
Inner function: 10
Functions with arrays
In C, the whole array cannot be passed as an argument to a function. However, you
can pass a pointer to an array without an index by specifying the array’s name.
Syntax:
Mentioning the size of the array is optional. So the syntax can be written as:
In both of the above syntax, even though we are defining the argument as array it will still be
passed as a pointer. So we can also write the syntax as:
#include <stdio.h>
#include <stdlib.h>
// Note that arr[] for fun is just a pointer even if square brackets are used. It is same as
void main()
int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
func(arr);
Output
As we can see,
The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes which is =
sizeof(int) * 8 = 4 * 8 = 32 bytes.
But in the function where the arr[] is passed as a parameter, the size of arr[] is shown as 8
bytes (which is the size of a pointer in C).
It is due to the fact that the array decays into a pointer after being passed as a parameter. One
way to deal with this problem is to pass the size of the array as another parameter to the
function. This is demonstrated in the below example.
Call by Value and Call by Reference
Functions can be invoked in two ways: Call by Value or Call by Reference. These
two ways are generally differentiated by the type of values passed to them as parameters.
The parameters passed to the function are called actual parameters whereas the
parameters received by the function are called formal parameters.
Call By Value in C
In call by value method of parameter passing, the values of actual parameters are
copied to the function’s formal parameters.
One is the original copy and the other is the function copy.
Any changes made inside functions are not reflected in the actual parameters of the caller.
#include <stdio.h>
// Function Prototype
void main()
// Pass by Values
}
// Swap functions that swaps two values
int t;
t = x;
x = y;
y = t;
Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20
Call by Reference in C
In call by reference method of parameter passing, the address of the actual parameters
is passed to the function as the formal parameters. In C, we use pointers to achieve call-by-
reference.
Both the actual and formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the actual parameters of the
caller.
// Function Prototype
// Main function
int main()
// Pass reference
return 0;
int t;
t = *x;
*x = *y;
*y = t;
}
Storage Classes
Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a
particular variable during the runtime of a program.
1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope).
2. extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this
can be overwritten/changed in a different block as well. So an extern variable is nothing but a
global variable initialized with a legal value where it is declared in order to be used
elsewhere. It can be accessed within any function/block The main purpose of using extern
variables is that they can be accessed between two different files which are part of a large
program.
3. static
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even
after they are out of their scope! Hence, static variables preserve the value of their last use in
their scope. So we can say that they are initialized only once and exist till the termination of
the program. Thus, no new memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
4. register
This storage class declares register variables that have the same functionality as that of the
auto variables. The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available. This makes the use of register
variables to be much faster than that of the variables stored in the memory during the runtime
of the program.
If a free registration is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program are declared with the register
keyword which improves the running time of the program. An important and interesting
point to be noted here is that we cannot obtain the address of a register variable using
pointers.
Syntax
Example
#include <stdio.h>
// declaring the variable which is to be made extern an initial value can also be initialized to x
int x;
void autoStorageClass()
printf("--------------------------------");
void registerStorageClass()
printf("--------------------------------");
}
void externStorageClass()
// telling the compiler that the variable x is an extern variable and has beendefined
//elsewhere (above the mainfunction)
extern int x;
x = 2;
printf("--------------------------------");
void staticStorageClass()
int i = 0;
printf("Declaring 'y' as static inside the loop.\nBut this declaration will occur only once” “
'y' is static.\nIf not, then every time the value of 'y' will be the declared value 5"
printf("\nLoop started:\n");
int p = 10;
y++;p++;
printf("\nLoop ended:\n");
printf("--------------------------------");
void main()
autoStorageClass();
registerStorageClass();
externStorageClass();
staticStorageClass();
}
Character array
A Character array is a derived data type in C that is used to store a collection of
characters or strings.
A char data type takes 1 byte of memory, so a character array has the memory of the
number of elements in the array. (1* number_of_elements_in_array).
Each character in a character array has an index that shows the position of the
character in the string.
The first character will be indexed 0 and the successive characters are indexed 1,2,3
etc...
The null character \0 is used to find the end of characters in the array and is always
stored in the index after the last character or in the last index.
Syntax
char name[size];
The name depicts the name of the character array and size is the length of the
character array.
The size can be greater than the length of the string but can not be lesser. If it is lesser
then the full string can't be stored and if it is greater the remaining spaces are just left
unused.
Example
#include <stdio.h>
void main() {
printf("%s\n", greeting);
}
String Functions
The C string functions are built-in functions that can be used for various operations and
manipulations on strings. These string functions can be used to perform tasks such as string
copy, concatenation, comparison, length, etc. The <string.h> header file contains these string
functions.
Some of the most commonly used String functions in the C programming language are
1. strcat() Function
The strcat() function in C is used for string concatenation. It will append a copy of the source
string to the end of the destination string.
Syntax
The terminating character at the end of dest is replaced by the first character of src.
Parameters
Return value
Example
#include <stdio.h>
void main()
Output
2. strlen() Function
The strlen() function calculates the length of a given string. It doesn’t count the null character ‘\0’.
Syntax
Parameters
Return Value
Example
void main()
//Calculate the length of the string using the strlen() function and store it in the variable 'length'
Output
String: GeeksforGeeks
Length: 13
3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two strings as arguments
and compares these two strings lexicographically.
Syntax
Parameters
Return Value
Example
#include <stdio.h>
#include <string.h>
void main()
// Compare 'str1' and 'str2' using strcmp() function and store the result in 'result1'
// Compare 'str1' and 'str1' using strcmp() function and store the result in 'result3'
Output
4. strcpy
The strcpy() is a standard library function in C and is used to copy one string to another. In
C, it is present in <string.h> header file.
Syntax
Parameters
Return Value
#include <stdio.h>
#include <string.h>
int main()
// defining strings
char dest[20];
strcpy(dest, source);
// printing result
return 0;
Output
Source: GeeksforGeeks
Destination: GeeksforGeeks
5. strchr()
The strchr() function in C is a predefined function used for string handling. This function is
used to find the first occurrence of a character in a string.
Syntax
Parameters
Here, str is the string and ch is the character to be located. It is passed as its int promotion,
but it is internally converted back to char.
Return Value
Example
#include <stdio.h>
#include <string.h>
int main()
char ch = 'e';
// Search for the character 'e' in the string Use the strchr function to find the first occurrence of 'e' in the string
//Character 'e' is found, calculate the index by subtracting the result pointer from the str pointer
if (result != NULL) {
else {
return 0;
Output
Syntax
Parameters
Return Value
If the s2 is found in s1, this function returns a pointer to the first character of the s2 in s1,
otherwise, it returns a null pointer.
Example
#include <stdio.h>
#include <string.h>
int main()
char* result;
// Find the first occurrence of 's2' within 's1' using strstr() function and assign the result to 'result'
else {
// If 'result' is NULL, it means the substring was not found, so print appropriate message
return 0;
Output
7. strtok()
The strtok() function is used to split the string into small tokens based on a set of delimiter
characters.
Syntax
Parameters
#include <stdio.h>
#include <string.h>
int main()
return 0;