Ch 05 Functions and Macros
Ch 05 Functions and Macros
Type of Functions: -
1. Pre-defined Functions: -
Functions defined previously in the library are called as library functions. These functions
are declared in header files (.h) files and defined in (.lib) files. We can call them by
including their header files in our programs.
stdio.h: -
printf() Sends the formatted output to stdin.
scanf(). Scans and formats input from stdin.
putchar() Outputs a character on stdout.
getchar() gets a character from stdin.
puts() Outputs string and appends a newline character.
gets() Get a string from stdin.
fflush() Flushes a stream
fopen() Opens a stream
fclose( ) Closes a stream
feof() Tests if end-of-file has been reached on a stream
fprintf() Sends formatted output to stream
fscanf() Scans and formats input from a stream.
fputs() Outputs a string to a stream
fgets() Gets a string from a stream
Matrix Computers (Page 2 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
conio.h: -
getch() gets a character from console but does not echo to the screen
getche() gets a character from console, and echoes to the screen
putch() Outputs character to the text window on the screen
stdlib.h: -
exit() Terminates the program.
itoa() converts an integer to a string.
ftoa() converts a float to a string
atoi() Converts string of digits to integer.
atof() converts a string to a floating point
random() Returns a random number between 0 and number – 1
randomize() initializes random number generator.
abs() gets the absolute value of an integer
math.h: -
RIX
AT
M
string.h: -
strlen() Function to calculate the length of the string
strcpy() Function to copy a string to another string
strcat() Function to concatenate(merge) strings.
strupr() Converts the given string to uppercase
strlwr() Converts the given string to lowercase
strrev() Function to reverse the given string.
strcmp() Function to compare two strings.
stricmp() Function to compare two strings ignoring their case.
strstr() Finds the first occurrence of string in another string.
Matrix Computers (Page 3 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Syntax of Functions: -
The syntax of function can be divided into 3 parts:
1. Function Declaration or prototype
2. Function Calls
3. Function Definition
1. Function Declaration: -
We must declare a function before call otherwise compiler will give an error. There is no
need to declare a function if we define the function before call. The declaration is also called as
prototype. The declaration of a function is not necessary if the output type is an integer value. In
some C compilers declaration is not required for all the function.
2. 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. The function call is the way of using the
function. A function is declared once, defined once but can be used a number of times in the
same program. When the compiler encounters the function call, the control of the program is
transferred to the function definition the function is then executed line by line and a value is
RIX
AT
M
returned at the end. If function main() calls a function sum() then main() is the calling function
and sum() is called function.
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
3. 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
Matrix Computers (Page 4 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
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 function definition
does not terminate with a semicolon. A function may have more than one return statement but
any one will work. It can be used as:
if (a!=0)
return(a);
else
return(1);
While it is possible to pass any number of arguments to a function, the called statement returns
only one value at a call. The return statement can be used as:
return;
or
return(value);
The first return without any value, it acts much as the closing of the braces of the function
definition.
The below example serves as both a function definition and a declaration.
RIX
AT
M
Multiple Return: -
We can’t return multiple values from a function. If we try to return multiple values then
only the last value will be returned because comma operator works from left to right but returns
right most value.
int f1(int a, int b, int c){
return a, b, c;
}
int main(){
int ans;
ans=f1(5,6,7);
printf(“%d”, ans); // 7
}
RIX
AT
M
void function: -
If a function does not return any value, then it is called as void function. void is a keyword
in c and it denotes type less datatype. It means nothing.
It is better to return the result from the function sqr to main function and then print in main
function but if we want to print the result in the function sqr then we can use void like this.
void sqr(int x){
printf(“%d”,x*x);
}
int main(){
Matrix Computers (Page 6 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
int n;
printf(“Enter a number”);
scanf(“%d”,&n);
sqr(n);
return(0);
}
It is not a better option to print the result in function but sometimes there are multiple
results and we can’t return multiple values from a function to main function then we can print all
results in function itself like this: -
void swap(int x,int y){
int t=x;
x=y;
y=t;
printf(“After swap values are %d,%d”,x,y);
}
int main(){
int a,b;
printf(“Enter 2 integers:”);
scanf(“%d%d”,&a,&b);
swap(a,b);
return(0);
}
Note: - We can’t return multiple values from a function but using pointer we can return multiple
values which will be covered in pointer chapter later.
RIX
AT
M
printf(“%d”,x); //6
return(0);
}
main function: -
main function is a user defined function. Every program must have a main function
because execution starts from main function. It is the first function to be called automatically. It
is possible to write complete program using only the main program but this is not a good option.
It will be difficult to understand and test the program as it becomes too large and too complex.
But if the same program is broken into small functions, then this program will be easy to
understand and test. We can write main function in two ways: -
1. Returning value from main function: -
We return 0 value to indicate that the program is successful and we return 1 or any
non zero value to indicate failure. It is good practice to return some value from main.
This 0 or 1 is of type int so we type int before main function.
int main(){
return(0);
}
void main(){
Note: - main function can also accepts arguments and this is called as command line arguments
and this will be covered after array.
int main(int argc, char *argv[]){
return(0);
}
printf(“Enter a integer:”);
scanf(“%d”,&x);
return x;
}
int main(){
int n;
n=getInteger();
if(n%2==0)
printf(“Number is Even.”);
else
printf(“Number is Odd.”);
return(0);
}
int a,b;
printf(“Enter 2 integers:”);
scanf(“%d%d”,&a,&b);
swap(a,b);
return(0);
}
Advantages of Functions in C: -
RIX
AT
M
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Slow execution of the program due to multiple jumps in calling a function. When we
call a function program control will jump from call to definition and then when we
return value from function then it will jump back from definition to call.
Macro Function: -
We already know that it is time consuming to call a function but If the function is small
(mostly single line), we can solve this problem by using a macro function. Macro function is
defined by #define directive. Whenever a macro name is encountered by the compiler, it
Matrix Computers (Page 10 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
replaces the name with the definition of the macro. Macro definitions should not be terminated
by a semi-colon(;). These macros are the same as a function call. It replaces the entire code
instead of a function name.
Example: -
#define sum(x,y) x+y
int main(){
printf(“\n%d”,sum(5,4));
printf(“\n%d”,sum(5,4)*sum(5,4)); //Output should be 81(9*9) but it will
//produce 29(5+4*5+4)
return(0);
}
Example: -
#define sum(x,y) (x+y)
int main(){
printf(“\n%d”,sum(5,4));
printf(“\n%d”,sum(5,4)*sum(5,4)); //81(5+4)*(5+4)
return(0);
}
Example: -
#define mult(x,y) (x*y)
int main(){
printf(“\n%d”,mult(5+4,5+4)); //output should be 81(9*9) but it will
//produce 29(5+4*5+4)
return(0);
}
All individual variables in the macro code should also enclosed in parenthesis.
Example: -
#define mult(x,y) ((x)*(y))
int main(){
Matrix Computers (Page 11 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
printf(“\n%d”,mult(5+4,5+4)); //81
return(0);
}
If we put a space between the macro name and the parentheses in the macro definition, then
the macro will not work.
#define sum (x,y) (x+y) //wrong
A multi-line macro can also be defined by placing a backward slash at the end of each
line except the last. This feature permits a single macro to be represented as compound
statement.
#include <stdio.h>
#define display(num, str) { \
printf("%d", num); \
printf(" is"); \
printf(" %s number", str); \
printf("\n"); \
}
int main(){
int n;
printf("Enter a number: ");
scanf("%d", &n);
if(n%2==0)
display(n, "Odd");
RIX
AT
M
else
display(n, "Even");
return 0;
}
Storage class decides the memory location of a variable. Memory location can be
1. Main Memory (RAM). 2. CPU registers. It decides the default value of a variable (Zero value
or garbage value). It also decides the scope & lifetime of a variable. Scope indicates the region
over which the variable’s declaration has an effect or in other words that particular variable can
be used. The four different kinds of scopes are global, function, block and prototype. There are
4 storage classes:-
1. Automatic storage class (auto)
2. Static storage class (static)
3. External storage class (extern)
4. Register storage class. (register)
int a=5;
printf(“%d ”, a);
prn();
prn();
prn();
}
void prn()
{
int a=10;
a++;
printf(“%d ”,a);
}
Output: 5 11 11 11
Here in the above example the two variables have the same name but they have different
scope. Variable a in prn() has local scope so every time prn() is called a new copy of a
will be generated.
void prn();
main()
{
prn();
prn();
prn();
}
void prn()
{
static int a=10;
a++;
printf(“%d ”,a);
}
Output:11 12 13
In the above example only a single copy of variable a will be created and this single copy will be
used every time prn() is called, so it will increment the last function call value of variable a.
thus wasting a lot of memory unnecessarily. The external variables are declared as extern int
c; It is also used when the variables of one program have to be used in some other programs
also for example: -
File1.c File2.c
#include ”File2.c” extern int a; /*Variable declaration*/
int a; /*Variable definition */ void func()
main() {
{ a=10;
a= 5; }
func();
printf(“%d”,a);
}
Output: 10
Variable a will get memory in File1.c. Because it is defined outside the function so
it is called as external variable and its scope is global. It can also be used in another
file File2.c. variable a used in both files is same. But when we compile the File2.c
we have to imform the compiler that variable a will come from outside so we have
declared a as extern int a;(no memory allocation at this time), but if we declare it
as int a; then compiler will treat it as a new variable.
to be used a number of times. However if a register is not free, auto storage class is used and
the execution is carried on. The CPU registers are 2 bytes long. So their maximum range is
equal to that of int. float values can not be stored in register. Even if we say register float x, auto
is assumed for x. The variable for this class are declared as, register int d;
Summary: -
Storage Class Memory Default Value Scope Lifetime
Auto Main memory Garbage Local Local
(RAM)
Static Main memory Zero Local Global
(RAM)
Extern Main memory Zero Global Global
(RAM)
Register CPU Registers Garbage Local Local
Recursion: -
Recursion is the process of calling a function itself repeatedly until a particular condition
is met. A function that calls itself directly or indirectly is called a recursive function and such kind
of function calls are called recursive calls.
A function is called recursive if a statement within the body of a function calls the same
function. Sometimes called as 'circular definition', recursion is a function calling itself in the
Matrix Computers (Page 14 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
definition. A recursive function should have two parts recursive statement & a termination
condition.
Suppose we want to calculate the factorial of an integer. As we know, the factorial of a
number is the product of all the integers between 1 and that number. Factorial of 4 can be
expressed as 4! = 4 * 3! Where ! stands for factorial. Thus the factorial of a number can be
expressed in the form of itself. Hence this can be programmed using recursion.
Example: -
int fact (int);
main()
{
int n,ans;
printf(“Enter a number: “);
scanf(“%d”,&n);
ans = fact(n); /*function call */
printf(“factorial = %d”,ans);
getch();
}
int fact(int n)
{
if(n= =0) /*terminating condition*/
return (1);
return (n*fact(n-1)); /*recursive statement*/
}
Now let us evaluate this program:
RIX
AT
M
Assuming the value of n is 3 when the control of the program is passed from the main()
function the function fact. Since n is not equal to 0 so the condition is false and the recursive
statement is executed.
3*fact(2)
now fact(2) is the calling function and thus the control of the program again reaches the
beginning of the definition. Still the terminating condition is false so the recursive statement is
executed.
2*fact(1)
again fact(1) is the calling function and thus the control of the program again reaches the
beginning of the definition. Still the terminating condition is false so the recursive statement is
executed.
1 * fact(0)
now the condition is true so the answer to the calling function(fact(0)) will be 1 and so on.
Thus the sequence of acts will be:
fact(3)=3 * fact(2)
fact(2)=2 * fact(1)
fact(1)=1 * fact(0)
When we use a recursive program a stack is used to organize the data. Stack is a Last
In First Out (LIFO) data structure. This means that the last item to be stored (push operation) in
the stack will be the first one to come (pop operation) out. In the above program when the fact(2)
is called the value 3 will be stored in the stack. Similarly when fact(1) is called the value 2 will be
stored at the top of 3 on the stack.
Matrix Computers (Page 15 of 15)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Now when the fact(0) returns 1. it will be multiplied to the first value in the stack i.e. 1.
This result will be multiplied to the second waiting value of the stack i.e. 2 and so on.
When a function in its definition calls another function it is called chaining. Recursion is a
special type of chaining where a function calls itself.
e.g.:
main()
{
printf(“Matrix\n”);
main();
}
when executed the program will give the output as :
Matrix
Matrix
Matrix
_
_
The execution of any recursive function can continue indefinitely so to bring the execution
to the end a terminating condition is applied.
Advantages of Recursion: -
The advantages of using recursive methods over other methods are:
1. Recursion can effectively reduce the length of the code.
2. Some problems are easily solved by using recursion like the tower of Hanoi and
tree traversals.
RIX
AT
M
3. Data structures like linked lists, trees, etc. are recursive in nature so recursive
methods are easier to implement for these data structures.
Disadvantages of Recursion: -
As with almost anything in the world, recursion also comes with certain limitations some of
which are:
1. Recursive functions make our program a bit slower due to function call overhead.
2. Recursion functions always take extra memory space.