0% found this document useful (0 votes)
2 views

C 4th Unit

This document provides an overview of C functions, including their syntax, types, return values, and categories. It covers function declarations, definitions, calls, and the differences between call by value and call by reference. Additionally, it discusses storage classes and their characteristics, such as auto, extern, static, and register.

Uploaded by

Revathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C 4th Unit

This document provides an overview of C functions, including their syntax, types, return values, and categories. It covers function declarations, definitions, calls, and the differences between call by value and call by reference. Additionally, it discusses storage classes and their characteristics, such as auto, extern, static, and register.

Uploaded by

Revathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit IV

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

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 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();

printf("Test Value %d", capturedValue);

printf("Test Value %d",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:

1. Function with no arguments and no return value


2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and with return value
Function with No Arguments and No Return Value
Functions that have no arguments and no return values. Such functions can either be
used to display information or to perform any task on global variables.

Syntax

// void return type with no arguments

void function_name()

// no return value

return;

Example

// C program to use function with no argument and no return values

#include <stdio.h>

void sum()

int x, y;

printf("Enter x and y\n"); scanf("%d %d", &x, &y);

printf("Sum of %d and %d is: %d", x, y, 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

// C program to use function with no argument and with return values

#include <stdio.h>

int sum()

int x, y, s = 0;

printf("Enter x and y\n");

scanf("%d %d", &x, &y);

s = x + y;

return s;

int main()

printf("Sum of x and y is %d", sum());

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

void function_name(type1 argument1, type2 argument2,...typeN argumentN)

// Program

return;

Example

// C program to use function with argument and no return values

#include <stdio.h>

void sum(int x, int y)

printf("Sum of %d and %d is: %d", x, y, x + y);

int main()

int x, y;

printf("Enter x and y\n");

scanf("%d %d", &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

return_type function_name(type1 argument1, type2 argument2,...typeN argumentN)

// program

return value;

Example

// C program to use function with argument and with return values

#include <stdio.h>

int sum(int x, int y)

return x + y;

int main()

int x, y;

printf("Enter x and y\n");

scanf("%d %d", &x, &y);

// function call

printf("Sum of %d and %d is: %d", x, y, sum(x, y));

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() {

printf("Inner function: %d\n", x);

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.

In C, we have three ways to pass an array as a parameter to the function.

Syntax:

In the function definition, use the following syntax:

return_type foo ( array_type array_name[size], ...);

Mentioning the size of the array is optional. So the syntax can be written as:

return_type foo ( array_type array_name[], ...);

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:

return_type foo ( array_type* array_name, ...);


Example: Checking Size After Passing Array as Parameter

#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 fun(int *arr) or void fun(int arr[size])

void func(int arr[8])

printf("Size of arr[] in func(): %d bytes", sizeof(arr));

void main()

int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };

printf("Size of arr[] in main(): %dbytes\n", sizeof(arr));

func(arr);

Output

Size of arr[] in main(): 32bytes

Size of arr[] in func(): 8 bytes

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.

There are two copies of parameters stored in different memory locations.

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.

Example of Call by Value

The following example demonstrates the call-by-value method of parameter passing

#include <stdio.h>

// Function Prototype

void swapx(int x, int y);

void main()

int a = 10, b = 20;

// Pass by Values

swapx(a, b); // Actual Parameters

printf("In the Caller:\na = %d b = %d\n", a, b);

}
// Swap functions that swaps two values

void swapx(int x, int y) // Formal Parameters

int t;

t = x;

x = y;

y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

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.

Example of Call by Reference

The following C program is an example of a call-by-reference method.


#include <stdio.h>

// Function Prototype

void swapx(int*, int*);

// Main function

int main()

int a = 10, b = 20;

// Pass reference

swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;

// Function to swap two variables by references

void swapx(int* x, int* y) // Formal Parameters

int t;

t = *x;

*x = *y;

*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);

}
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

storage_class var_data_type var_name;

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("\nDemonstrating auto class\n\n");

// declaring an auto variable (simply writing "int a=32;" works as well)

auto int a = 32;

// printing the auto variable 'a'

printf("Value of the variable 'a' declared as auto: %d\n", a);

printf("--------------------------------");

void registerStorageClass()

printf("\nDemonstrating register class\n\n");

// declaring a register variable

register char b = 'G';

// printing the register variable 'b'

printf("Value of the variable 'b' declared as register: %d\n",b);

printf("--------------------------------");

}
void externStorageClass()

printf("\nDemonstrating extern class\n\n");

// telling the compiler that the variable x is an extern variable and has beendefined
//elsewhere (above the mainfunction)

extern int x;

// printing the extern variables 'x'

printf("Value of the variable 'x'declared as extern: %d\n",x);

// value of extern variable x modified

x = 2;

// printing the modified values of extern variables 'x'

printf("Modified value of the variable 'x'declared as extern: %d\n", x);

printf("--------------------------------");

void staticStorageClass()

int i = 0;

printf("\nDemonstrating static class\n\n");

// using a static variable 'y'

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"

" as in the case of variable 'p'\n");

printf("\nLoop started:\n");

for (i = 1; i < 5; i++) {

// Declaring the static variable 'y'


static int y = 5;

// Declare a non-static variable 'p'

int p = 10;

y++;p++;

// printing value of y at each iteration

printf("\nThe value of 'y', declared as static, in %d iteration is %d\n”,i, y);

// printing value of p at each iteration

printf("The value of non-static variable 'p', in %d iteration is %d\n",i, p);

printf("\nLoop ended:\n");

printf("--------------------------------");

void main()

printf("A program to demonstrateStorage Classes in C\n\n");

// To demonstrate auto Storage Class

autoStorageClass();

// To demonstrate register Storage Class

registerStorageClass();

// To demonstrate extern Storage Class

externStorageClass();

// To demonstrate static Storage Class

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() {

char greeting[20] = "Hello, world!";

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 2. strlen() Function 3. strcmp() Function 4. strcpy() Function

5. strchr() Function 6. strstr() Function 7. strtok() Function

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

char* strcat(char* dest, const char* src);

The terminating character at the end of dest is replaced by the first character of src.

Parameters

dest: Destination string

src: Source string

Return value

The strcat() function returns a pointer to the dest string.

Example

#include <stdio.h>

void main()

{ char dest[50] = "This is an";

char src[50] = " example";

printf("dest Before: %s\n", dest);

// concatenating src at the end of dest


strcat(dest, src);

printf("dest After: %s", dest); }

Output

dest Before: This is an

dest After: This is an example

2. strlen() Function
The strlen() function calculates the length of a given string. It doesn’t count the null character ‘\0’.

Syntax

int strlen(const char *str);

Parameters

str: It represents the string variable whose length we have to find.

Return Value

strlen() function in C returns the length of the string.

Example

#include <stdio.h> #include <string.h>

void main()

{ char str[] = "GeeksforGeeks";

//Calculate the length of the string using the strlen() function and store it in the variable 'length'

size_t length = strlen(str);

printf("String: %s\n", str);

printf("Length: %zu\n", 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

int strcmp(const char *str1, const char *str2);

Parameters

str1: This is the first string to be compared.

str2: This is the second string to be compared.

Return Value

If str1 is less than str2, the return value is less than 0.

If str1 is greater than str2, the return value is greater than 0.

If str1 is equal to str2, the return value is 0.

Example

#include <stdio.h>

#include <string.h>

void main()

// Define a string 'str1' and initialize it with "Geeks"

char str1[] = "Geeks";

// Define a string 'str2' and initialize it with "For"

char str2[] = "For";

// Define a string 'str3' and initialize it with "Geeks"

char str3[] = "Geeks";

// Compare 'str1' and 'str2' using strcmp() function and store the result in 'result1'

int result1 = strcmp(str1, str2);


// Compare 'str2' and 'str3' using strcmp() function and store the result in 'result2'

int result2 = strcmp(str2, str3);

// Compare 'str1' and 'str1' using strcmp() function and store the result in 'result3'

int result3 = strcmp(str1, str1);

// Print the result of the comparison between 'str1' and 'str2'

printf("Comparison of str1 and str2: %d\n", result1);

// Print the result of the comparison between 'str2' and 'str3'

printf("Comparison of str2 and str3: %d\n", result2);

// Print the result of the comparison between 'str1' and 'str1'

printf("Comparison of str1 and str1: %d\n", result3);

Output

Comparison of str1 and str2: 1

Comparison of str2 and str3: -1

Comparison of str1 and str1: 0

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

char* strcpy(char* dest, const char* src);

Parameters

dest: Pointer to the destination array where the content is to be copied.

src: string which will be copied.

Return Value

strcpy() function returns a pointer pointing to the output string.


Example

#include <stdio.h>

#include <string.h>

int main()

// defining strings

char source[] = "GeeksforGeeks";

char dest[20];

// Copying the source string to dest

strcpy(dest, source);

// printing result

printf("Source: %s\n", source);

printf("Destination: %s\n", dest);

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

char *strchr(const char *str, int c);

Parameters

str: specifies the pointer to the null-terminated string to be searched in.


ch: specifies the character to be searched for.

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

It returns a pointer to the first occurrence of the character in the string.

Example

#include <stdio.h>

#include <string.h>

int main()

char str[] = "GeeksforGeeks";

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

char* result = strchr(str, ch);

//Character 'e' is found, calculate the index by subtracting the result pointer from the str pointer

if (result != NULL) {

printf("The character '%c' is found at index %ld\n", ch, result - str);

else {

printf("The character '%c' is not found in the string\n", ch);

return 0;

Output

The character 'e' is found at index 1


6. strstr()
The strstr() function in C is used to search the first occurrence of a substring in another
string.

Syntax

char *strstr (const char *s1, const char *s2);

Parameters

s1: This is the main string to be examined.

s2: This is the sub-string to be searched in the s1 string.

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.

It returns s1 if s2 points to an empty string.

Example

#include <stdio.h>

#include <string.h>

int main()

// Define a string 's1' and initialize it with "GeeksforGeeks"

char s1[] = "GeeksforGeeks";

// Define a string 's2' and initialize it with "for"

char s2[] = "for";

// Declare a pointer 'result' to store the result of strstr()

char* result;

// Find the first occurrence of 's2' within 's1' using strstr() function and assign the result to 'result'

result = strstr(s1, s2);


if (result != NULL) {

// If 'result' is not NULL, it means the substring was found, so print it

printf("Substring found: %s\n", result);

else {

// If 'result' is NULL, it means the substring was not found, so print appropriate message

printf("Substring not found.\n");

return 0;

Output

Substring found: forGeeks

7. strtok()

The strtok() function is used to split the string into small tokens based on a set of delimiter
characters.

Syntax

char * strtok(char* str, const char *delims);

Parameters

str: It is the string to be tokenized.

delims: It is the set of delimiters


Example

#include <stdio.h>

#include <string.h>

int main()

char str[] = "Geeks,for.Geeks";

// Delimiters: space, comma, dot, exclamation mark

const char delimiters[] = ",.";

// Tokenize the string

char* token = strtok(str, delimiters);

while (token != NULL) {

printf("Token: %s\n", token);

token = strtok(NULL, delimiters);

return 0;

You might also like