सी, पायथन, जावास्क्रिप्ट, गो, रस्ट, सॉलिडिटी जैसी भाषाओं और कंप्यूटर साइंस के बुनियादी और गणित के उन्नत सिद्धांतों को हिंदी में पढ़ने के लिए संपर्क करें। हम वेबसाइट और सॉफ्टवेयर भी बनाते हैं।
C enables programmers to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others. Every function in the program is supposed to perform a well-defined task. Therefore, the code of one function is completely insulated from the other functions.
Every function interfaces to the outside world in terms of how information is transferred to it and how results generated by it are transmitted back. This interface is specified by the function name. For example, look at Figure 4.1 which explains how the main() function calls another function to perform a well-defined task.
From the figure we can see that main() calls a function named func1(). Therefore, main() is known as the calling function and func1() is known as the called function. The moment the compiler encounters a function call, instead of executing the next statement in the calling function, the control jumps to the statements that are part of the called function. After the called function is executed, the control is returned back to the calling function.
It is not necessary that the main() function can call only one function, it can call as many functions as it wants and as many times as it wants. For example, a function call placed within a for loop, while loop, or do-while loop can call the same function multiple times until the condition holds true.
Another point is that it is not only the main() function that can call other functions. A function can call any other function. For example, look at Figure 4.2 which shows one function calling another, and this function in turn calling some other function. From this we see that every function encapsulates a set of operations and when called it returns information to the calling function.
4.1.1 Why are Functions Needed?
Let us analyse the reasons for segmenting a program into manageable chunks as it is an important aspect of programming.
Dividing a program into separate well-defined functions facilitates each function to be written and tested separately. This simplifies the process of getting the total program to work. Figure 4.3 shows that the main() function calls other functions for dividing the entire code into smaller sections (or functions). This approach is referred to as the top-down approach.
Figure 4.3 Top-down approach of solving a problem
Main Function
/ | \
Function A Function B Function C
/ \
Function B1 Function B2
Understanding, coding, and testing multiple separate functions are far easier than doing it for one big function.
If a big program has to be developed without the use of any function other than main(), then there will be countless lines in the main() function and maintaining this program will be very difficult. A large program size is a serious issue in micro-computers where memory space is limited.
All the libraries in C contain a set of functions that the programmers are free to use in their programs. These functions have been pre-written and pre-tested, so the programmers can use them without worrying about their code details. This speeds up program development, by allowing the programmer to concentrate only on the code that he has to write.
When a big program is broken into comparatively smaller functions, then different programmers working on that project can divide the workload by writing different functions.
Like C libraries, programmers can also write their own functions and use them at different points in the main program or in any other program that needs its functionalities.
Consider a program that executes a set of instructions repeatedly n times, though not continuously. In case the instructions had to be repeated continuously for n times, they can be placed within a loop. But if these instructions have to be executed abruptly from anywhere within the program code, then instead of writing these instructions wherever they are required, a better idea is to place these instructions in a function and call that function wherever required. Figure 4.4 explains this concept.
Figure 4.4 Function func1() called twice from main()
In the second chapter we have discussed that when we execute a C program, the operating system calls the main() function of the program which marks the entry point for the execution. When the program is executed, the main() returns some value to the operating system.
Any function (including main()) can be compared to a black box that takes in input, processes it, and then produces the result. However, we may also have a function that does not take any inputs at all, or the one that does not return anything at all.
While using functions we will be using the following terminologies:
A function f that uses another function g is known as the calling function and g is known as the called function.
The inputs that a function takes are known as arguments/parameters.
When a called function returns some result back to the calling function, it is said to return that result.
The calling function may or may not pass parameters to the called function. If the called function accepts arguments, the calling function will pass parameters, else it will not do so.
Function declaration is a declaration statement that identifies a function with its name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function, followed by the body of the function containing the executable code for that function.
4.3 FUNCTION DECLARATION/FUNCTION PROTOTYPE
Before using a function, the compiler must know about the number of parameters and the type of parameters that the function expects to receive and the data type of the value that it will return to the calling function. Placing the function declaration statement prior to its use enables the compiler to make a check on the arguments used while calling that function.
The general format for declaring a function that accepts some arguments and returns some value as a result can be given as:
Here, function_name is a valid name for the function. Naming a function follows the same rules as naming variables. A function should have a meaningful name that must specify the task that the function will perform. The function name is used to call it for execution in a program. Every function must have a different name that indicates the particular job that the function does.
return_data_type specifies the data type of the value that will be returned to the calling function as a result of the processing performed by the called function. data_type variable1, data_type variable2, ... is a list of variables of specified data types. These variables are passed from the calling function to the called function. They are also known as arguments or parameters that the called function accepts to perform its task. Table 4.1 shows examples of valid function declarations in C.
Table 4.1 Valid function declarations
Function declaration
Use of the function
char convert_to_uppercase(char ch);
Converts a character to upper case. The function receives a character as an argument, converts it into upper case and returns the converted character back to the calling function.
float avg(int a, int b);
Calculates average of two integer numbers a and b received as arguments. The function returns a floating point value.
int find_largest(int a, int b, int c);
Finds the largest of three numbers — a, b, and c received as arguments. An integer value which is the largest of the three numbers is returned to the calling function.
double multiply(float a, float b);
Multiplies two floating point numbers a and b that are received as arguments and returns a double value.
void swap(int a, int b);
Swaps or interchanges the value of integer variables a and b received as arguments. The function returns no value, therefore the return type is void.
void print(void);
The function is used to print information on screen. The function neither accepts any value as argument nor returns any value. Therefore, the return type is void and the argument list contains void data type.
Things to remember about function declaration:
After the declaration of every function, there should be a semicolon. If the semicolon is missing, the compiler will generate an error message.
The function declaration is global. Therefore, the declared function can be called from any point in the program.
Programming Tip: Though optional, use argument names in the function declaration.
Use of argument names in the function declaration statement is optional. So both declaration statements are valid in C.
int func(int, char, float);
or
int func(int num, char ch, float fnum);
A function cannot be declared within the body of another function.
A function having void as its return type cannot return any value.
A function having void as its parameter list cannot accept any value. So the function declared as
void print(void);
or
void print()
does not accept any input/arguments from the calling function.
If the function declaration does not specify any return type, then by default, the function returns an integer value. Therefore when a function is declared as
sum(int a, int b);
Then the function sum accepts two integer values from the calling function and in turn returns an integer value to the caller.
Some compilers make it compulsory to declare the function before its usage while other compilers make it optional. However, it is a good practice to always declare the function before its usage as it allows error checking on the arguments in the function call.
4.4 FUNCTION DEFINITION
When a function is defined, space is allocated for that function in the memory. A function definition comprises two parts:
Function header
Function body
Programming Tip: It is an error to place a semicolon after the function header in the function definition.
The syntax of a function definition can be given as:
The number of arguments and the order of arguments in the function header must be same as that given in the function declaration statement.
Programming Tip: The parameter list in the function definition as well as function declaration must match.
While return_data_type function_name(data_type variable1, data_type variable2, ...) is known as the function header, the rest of the portion comprising of program statements within { } is the function body which contains the code to perform the specific task.
The function header is same as function declaration. The only difference between the two is that a function header is not followed by a semicolon. The list of variables in the function header is known as the formal parameter list. The parameter list may have zero or more parameters of any data type. The function body contains instructions to perform the desired computation in a function.
Programming Tip: A function can be defined either before or after main().
The function definition itself can act as an implicit function declaration. So the programmer may skip the function declaration statement in case the function is defined before being used.
Note: The argument names in the function declaration and function definition need not be the same. However, the data types of the arguments specified in function declaration must match with that given in function definition.
4.5 FUNCTION CALL
The function call statement invokes the function. When a function is invoked the compiler jumps to the called function to execute the statements that are part of that function. Once the called function is executed, the program control passes back to the calling function.
Function call statement has the following syntax:
function_name(variable1, variable2, ...);
When the function declaration is present before the function call, the compiler can check if the correct number and type of arguments are used in the function call and the returned value, if any, is being used reasonably.
Function definitions are often placed in separate header files which can be included in other C source files that wish to use these functions. For example, the header file stdio.h contains the definition of scanf and printf functions. We simply include this header file and call these functions without worrying about the code to implement their functionality.
Note: List of variables used in function call is known as actual parameter list. The actual parameter list may contain variable names, expressions, or constants.
4.5.1 Points to Remember While Calling Functions
The following points are to be kept in mind while calling functions:
Programming Tip: A logical error will be generated if the arguments in the function call are placed in the wrong order.
Function name and the number and type of arguments in the function call must be same as that given in the function declaration and function header of the function definition.
If the parameters passed to a function are more than what it is specified to accept then the extra arguments will be discarded.
If the parameters passed to a function are less than what it is specified to accept then the unmatched arguments will be initialized to some garbage value.
Names (and not the types) of variables in function declaration, function call, and header of function definition may vary.
If the data type of the argument passed does not match with that specified in the function declaration then either the unmatched argument will be initialized to some garbage value or a compile time error will be generated.
Arguments may be passed in the form of expressions to the called function. In such cases, arguments are first evaluated and converted to the type of formal parameter and then the body of the function gets executed.
The parameter list must be separated with commas.
If the return type of the function is not void, then the value returned by the called function may be assigned to some variable as shown in the following statement.
1. Write a program to add two integers using functions.
#include <stdio.h>
// FUNCTION DECLARATION
int sum(int a, int b);
int main()
{
int num1, num2, total = 0;
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
total = sum(num1, num2);
// FUNCTION CALL
printf("\n Total = %d", total);
return 0;
}
// FUNCTION DEFINITION
int sum (int a, int b) // FUNCTION HEADER
{ // FUNCTION BODY
int result;
result = a + b;
return result;
}
Output
Enter the first number: 20
Enter the second number: 30
Total = 50
The variables declared within the function and its parameters are local to that function. The programmer may use same names for variables in other functions. This eliminates the need for thinking and keeping unique names for variables declared in all the functions in the program.
Programming Tip: It is an error to use void as the return type when the function is expected to return a value to the calling function.
In the sum() function, we have declared a variable result just like any other variable. Variables declared within a function are called automatic local variables because of two reasons.
First, they are local to the function. So, their effect (in terms of scope, lifetime, or accessibility) is limited to the function. Any change made to these variables is visible only in that function.
Second, they are automatically created whenever the function is called and cease to exist after control exits the function.
Note: A function cannot be used on the left side of an assignment statement. Therefore writing, func(10) = 100; is invalid in C, where func is a function that accepts an integer value.
4.6 RETURN STATEMENT
The return statement is used to terminate the execution of a function and returns control to the calling function. When the return statement is encountered, the program execution resumes in the calling function at the point immediately following the function call. Refer Figure 4.2 in which the control passes from the called function to the calling function when the return statement is encountered.
Programming Tip: It is an error to use a return statement in a function that has void as its return type.
A return statement may or may not return a value to the calling function. The syntax of return statement can be given as
return <expression>;
Here expression is placed in between angular brackets because specifying an expression is optional. The value of expression, if present, is returned to the calling function. However, in case expression is omitted, the return value of the function is undefined.
The expression, if present, is converted to the type returned by the function. A function that has void as its return type cannot return any value to the calling function. So in a function that has been declared with return type void, a return statement containing an expression generates a warning and the expression is not evaluated.
For functions that have no return statement, the control automatically returns to the calling function after the last statement of the called function is executed. In other words an implicit return takes place upon execution of the last statement of the called function, and control automatically returns to the calling function.
Note: The programmer may or may not place the expression in a return statement within parentheses. By default, the return type of a function is int.
Programming Tip: When the value returned by a function is assigned to a variable, then the returned value is converted to the type of the variable receiving it.
Programming Tip: An error is generated when the function does not return data of the specified type.
Programming Tip: A function that does not return any value cannot be placed on the right side of the assignment operator.
A function may have more than one return statement. For example, consider the program given below.
#include <stdio.h>
int check_relation(int a, int b);
int main()
{
int a=3, b=5, res;
res = check_relation(a, b);
if(res==0) // Test the returned value
printf("\n EQUAL");
if(res==1)
printf("\n a is greater than b");
if(res==-1)
printf("\n a is less than b");
return 0;
}
int check_relation(int a, int b)
{
if(a==b)
return 0;
else if(a>b)
return 1;
else
return -1;
}
Output
a is less than b
In the above program there are multiple return statements, but only one of them will get executed depending upon the condition. The return statement, like the break statement, is used to cause a premature termination of the function.
An expression appearing in a return statement is converted to the return type of the function in which the statement appears. If no implicit conversion is possible, the return statement is invalid. Since the return type of the function check_relation() is int, so the result either 0, 1, or -1 is evaluated as an integer.
We have mentioned earlier that the variables declared inside the function cease to exist after the last statement of the function is executed. So how can we return the value of sum to the program that adds two integers using a function? The answer to this question is that a copy of the value being returned is made automatically and this copy is available to the return point in the program.
4.6.1 Using Variable Number of Arguments
Some functions have a variable number of arguments and data types that cannot be known at the compile time. Typical examples of such functions include the printf() and scanf() functions. ANSI C offers a symbol called ellipsis to handle such functions. The ellipsis consists of three periods (...). It can be used as:
int func(char ch, ...);
The function declaration statement given above states that func is a function that has an arbitrary number and type of arguments. However, one must ensure that both the function declaration and function definition should use the ellipsis symbol.
4.7 PASSING PARAMETERS TO FUNCTIONS
When a function is called, the calling function may have to pass some values to the called function. We have been doing this in the programming examples given so far. We will now learn the technicalities involved in passing arguments/parameters to the called function.
There are two ways in which arguments or parameters can be passed to the called function. They include:
Call by value in which values of variables are passed by the calling function to the called function. The programs that we have written so far call functions using call-by-value method of passing parameters.
Call by reference in which address of variables are passed by the calling function to the called function.
4.7.1 Call by Value
Till now, we had been calling functions and passing arguments to them using call-by-value method. In the call-by-value method, the called function creates new variables to store the value of the arguments passed to it. Therefore, the called function uses a copy of the actual arguments to perform its intended task.
If the called function is supposed to modify the value of the parameters passed to it, then the change will be reflected only in the called function. In the calling function no change will be made to the value of the variables. This is because all the changes were made to the copy of the variables and not to the actual variables.
Programming Tip: It is legal to have multiple return statements in C.
To understand this concept, consider the code given below. The add() function accepts an integer variable num and adds 10 to it. In the calling function, the value of num = 2. In add(), the value of num is modified to 12 but in the calling function the change is not reflected.
#include <stdio.h>
void add(int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Since the called function uses a copy of num, the value of num in the calling function remains untouched. This concept can be more clearly understood from Figure 4.5.
Figure 4.5 Call-by-value method of argument passing
+-------+ +-------+
| 2 | | 2 |
+-------+ +-------+
num in the calling num in the calling function,
function is known as n in the
called function
+-------+ +-------+
| 2 | | 12 |
+-------+ +-------+
num in the calling n is modified in the
function remains unchanged called function
In the above program, the called function could not directly modify the value of the argument that was passed to it. In case the value has to be changed, then the programmer may use the return statement. This is shown in the following code.
#include <stdio.h>
int add (int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
num = add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
int add (int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
return n;
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
The following points are to be noted while passing arguments to a function using the call-by-value method.
When arguments are passed by value, the called function creates new variables of the same data type as the arguments passed to it.
The values of the arguments passed by the function are copied into the newly created variables.
Arguments are called by value when the called function does not need to modify the values of the original variables in the calling function.
Values of the variables in the calling function remain unaffected when the arguments are passed using call by value technique.
Therefore, call-by-value method of passing arguments to a function must be used only in two cases:
When the called function does not need to modify the value of the actual parameter. It simply uses the value of the parameter to perform its task.
When you want that the called function should only temporarily modify the value of the variables and not permanently. So although the called function may modify the value of the variables, these variables remain unchanged in the calling function.
Programming Tip: Using call by value method of passing values is preferred to avoid inadvertent changes to variables of the calling function in the called function.
Pros and Cons
The biggest advantage of using the call-by-value technique to pass arguments to the called function is that arguments can be variables (e.g., x), literals (e.g., 6), or expressions (e.g., x+1). The disadvantage is that copying data consumes additional storage space. In addition, it can take a lot of time to copy, thereby resulting in performance penalty, especially if the function is called many times.
4.7.2 Call by Reference
When the calling function passes arguments to the called function using call-by-value method, the only way to return the modified value of the argument to the caller is explicitly using the return statement. The better option when a function wants to modify the value of the argument is to pass arguments using call-by-reference technique.
In call by reference, we declare the function parameters as references rather than normal variables. When this is done any changes made by the function to the arguments it receives are visible in the calling function.
To indicate that an argument is passed using call by reference, an asterisk (*) is placed after the type in the parameter list. This way, changes made to the parameter in the called function will then be reflected in the calling function.
Hence, in call-by-reference method, a function receives an implicit reference to the argument, rather than a copy of its value. Therefore, the function can modify the value of the variable and that change will be reflected in the calling function as well. The following program uses this concept.
To understand this concept, consider the code given below.
#include <stdio.h>
void add (int *n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n);
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
Advantages
The advantages of using the call-by-reference technique of passing arguments are as follows:
Since arguments are not copied into new variables, it provides greater time and space efficiency.
The called function can change the value of the argument and the change is reflected in the calling function.
A return statement can return only one value. In case we need to return multiple values, pass those arguments by reference.
Disadvantages
However, the side-effect of using this technique is that when an argument is passed using call by address, it becomes difficult to tell whether that argument is meant for input, output, or both.
Now let us write a few programs that use both the call-by-value and the call-by-reference mechanisms.
2. Write a function to swap the value of two variables.
#include <stdio.h>
void swap_call_by_val(int, int);
void swap_call_by_ref(int *, int *);
int main()
{
int a=1, b=2, c=3, d=4;
printf("\n In main(), a = %d and b = %d", a, b);
swap_call_by_val(a, b);
printf("\n In main(), a = %d and b = %d", a, b);
printf("\n\n In main(), c = %d and d = %d", c, d);
swap_call_by_ref(&c, &d);
// address of the variables is passed
printf("\n In main(), c = %d and d = %d", c, d);
return 0;
}
void swap_call_by_val(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("\n In function (Call By Value Method) a = %d and b = %d", a, b);
}
void swap_call_by_ref(int *c, int *d)
{
int temp;
temp = *c;
// *operator used to refer to the value
*c = *d;
*d = temp;
printf("\n In function (Call By Reference Method) c = %d and d = %d", *c, *d);
}
Output
In main(), a = 1 and b = 2
In function (Call By Value Method) a = 2 and b = 1
In main(), a = 1 and b = 2
In main(), c = 3 and d = 4
In function (Call By Reference Method) c = 4 and d = 3
In main(), c = 4 and d = 3
3. Write a program to find biggest of three integers using functions.
#include <stdio.h>
int greater(int a, int b, int c);
int main()
{
int num1, num2, num3, large;
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
large = greater(num1, num2, num3);
printf("\n Largest number = %d", large);
return 0;
}
int greater(int a, int b, int c)
{
if(a>b && a>c)
return a;
if(b>a && b>c)
return b;
else
return c;
}
Output
Enter the first number : 45
Enter the second number: 23
Enter the third number : 34
Largest number = 45
4. Write a program to calculate area of a circle using function.
#include <stdio.h>
float cal_area(float r);
int main()
{
float area, radius;
printf("\n Enter the radius of the circle: ");
scanf("%f", &radius);
area = cal_area(radius);
printf("\n Area of the circle with radius %f = %f", radius, area);
return 0;
}
float cal_area(float radius)
{
return (3.14 * radius * radius);
}
Output
Enter the radius of the circle: 7
Area of the circle with radius 7 = 153.83
5. Write a program to convert time to minutes.
#include <stdio.h>
int convert_time_in_mins(int hrs, int minutes);
int main()
{
int hrs, minutes, total_mins;
printf("\n Enter hours and minutes: ");
scanf("%d %d", &hrs, &minutes);
total_mins = convert_time_in_mins(hrs, minutes);
printf("\n Total minutes = %d", total_mins);
return 0;
}
int convert_time_in_mins(int hrs, int mins)
{
mins = hrs*60 + mins;
return mins;
}
Output
Enter hours and minutes: 4 30
Total minutes = 270
6. Write a program to calculate P(n/r).
#include <stdio.h>
int Fact(int);
int main()
{
int n, r;
float result;
printf("\n Enter the value of n: ");
scanf("%d", &n);
printf("\n Enter the value of r: ");
scanf("%d", &r);
result = (float)Fact(n)/Fact(r);
printf("\n P(n/r): P(%d)/(%d) = %.2f", n, r, result);
return 0;
}
int Fact(int num)
{
int f=1, i;
for(i=num;i>=1;i--)
f = f*i;
return f;
}
Output
Enter the value of n: 4
Enter the value of r: 2
P(n/r): P(4)/(2) = 12.00
7. Write a program to calculate C(n/r).
#include <stdio.h>
int Fact(int);
int main()
{
int n, r;
float result;
printf("\n Enter the value of n: ");
scanf("%d", &n);
printf("\n Enter the value of r: ");
scanf("%d", &r);
result = (float)Fact(n)/(Fact(r)*Fact(n-r));
printf("\n C(n/r) : C(%d/%d) = %.2f", n, r, result);
return 0;
}
int Fact(int num)
{
int f=1, i;
for(i=num;i>=1;i--)
f = f*i;
return f;
}
Output
Enter the value of n: 4
Enter the value of r: 2
C(n/r): C(4)/(2) = 6.00
8. Write a program to sum the series—1/1! + 1/2! + 1/3! + ..... + 1/n!.
#include <stdio.h>
int Fact(int);
int main()
{
int n, f, i;
float result=0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
f=Fact(i);
result += 1/(float)f;
}
printf("\n The sum of the series 1/1! + 1/2! + 1/3!... = %.1f", result);
return 0;
}
int Fact(int num)
{
int f=1, i;
for(i=num;i>=1;i--)
f = f*i;
return f;
}
Output
Enter the value of n: 2
The sum of the series 1/1! + 1/2! + 1/3!... = 1.5
9. Write a program to sum the series—1/1! + 4/2! + 27/3! + ....
#include <stdio.h>
#include <math.h>
int Fact(int);
int main()
{
int n, i, NUM, DENO;
float sum=0.0;
printf("\n Enter the value of n");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
NUM = pow(i,i);
DENO = Fact(i);
sum += (float)NUM/DENO;
}
printf("\n 1/1! + 4/2! + 27/3! + ....= %.2f", sum);
return 0;
}
int Fact(int n)
{
int f=1, i;
for(i=n;i>=1;i--)
f=f*i;
return f;
}
Output
Enter the value of n: 3
1/1! + 4/2! + 27/3! + ....= 7.50
4.8 SCOPE OF VARIABLES
In C, all constants and variables have a defined scope. By scope we mean the accessibility and visibility of the variables at different points in the program. A variable or a constant in C has four types of scope: block, function, program, and file.
4.8.1 Block Scope
We have studied that a statement block is a group of statements enclosed within opening and closing curly brackets ({ }). If a variable is declared within a statement block then as soon as the control exits that block, the variable will cease to exist. Such a variable also known as a local variable is said to have a block scope.
So far we had been using local variables. For example, if we declare an integer x inside a function, then that variable is unknown to the rest of the program (i.e., outside that function). Blocks of statements may be placed one after the other in a program; such blocks that are placed at the same level are known as parallel blocks. However, a program may also contain a nested block, like a while loop inside main(). If an integer x is declared and initialized in main(), and then re-declared and re-initialized in a while loop, then the integer variable x will occupy different memory slots and will be considered as different variables. The following code reveals this concept:
Programming Tip: It is an error to use the name of a function argument as the name of a local variable.
#include <stdio.h>
int main()
{
int x = 10;
int i=0;
printf("\n The value of x outside the while loop is %d", x);
while (i<3)
{
int x = i;
printf("\n The value of x inside the while loop is %d", x);
i++;
}
printf("\n The value of x outside the while loop is %d", x);
return 0;
}
Output
The value of x outside the while loop is 10
The value of x inside the while loop is 0
The value of x inside the while loop is 1
The value of x inside the while loop is 2
The value of x outside the while loop is 10
Programming Tip: Try to avoid variable names that hides variables in outer scope.
You may get an error message while executing this code. This is because some C compilers make it mandatory to declare all the variables first before you use them, i.e., they permit declaration of variables right after the curly brackets of main() starts. Hence, we can conclude two things:
Variables declared with same names as those in outer block mask the outer block variables while executing the inner block.
In nested blocks, variables declared outside the inner blocks are accessible to the nested blocks, provided these variables are not re-declared within the inner block.
Note: In order to avoid error, a programmer must use different names for variables not common to inner as well as outer blocks.
4.8.2 Function Scope
Function scope indicates that a variable is active and visible from the beginning to the end of a function. In C, only the goto label has function scope. In other words, function scope is applicable only with goto label names. This means that the programmer cannot have the same label names inside a function.
Using goto statements is not recommended as it is not considered to be a good programming practice. We will not discuss the goto statement in detail here but we will take a look at an example code that demonstrates the function scope.
int main()
{
.
.
loop: /* A goto label has function scope */
.
.
goto loop; /* the goto statement */
.
.
return 0;
}
In this example, the label loop is visible from the beginning to the end of the main() function. Therefore, there should not be more than one label having the same name within the main() function.
4.8.3 Program Scope
Till now we have studied that variables declared within a function are local variables. These local variables (also known as internal variables) are automatically created when they are declared in the function and are usable only within that function. The local variables are unknown to other functions in the program. Such variables cease to exist after the function in which they are declared is exited and are re-created each time the function is called.
However, if you want a function to access some variables which are not passed to it as arguments, then declare those variables outside any function blocks. Such variables are commonly known as global variables and can be accessed from any point in the program.
Programming Tip: A global variable can be used from anywhere in the program whereas the local variable cease to exist outside the function in which it is declared.
Lifetime Global variables are created at the beginning of program execution and remain in existence throughout the period of execution of the program. These variables are known to all the functions in the program and are accessible to them for usage. Global variables are not limited to a particular function so they exist even when a function calls another function. These variables retain their value so that they can be used from every function in the program.
Place of Declaration The global variables are declared outside all the functions including main(). Although there is no specific rule that states where the global variables must be declared, it is always recommended to declare them on top of the program code.
Name Conflict If we have a variable declared in a function that has same name as that of the global variable, then the function will use the local variable declared within it and ignore the global variable. However, the programmer must not use names of global variables as the names of local variables, as this may lead to confusion and erroneous result.
Note: If a global variable is not initialized during its declaration then it is automatically initialized to zero by default.
Consider the following program.
#include <stdio.h>
int x = 10;
void print();
int main()
{
printf("\n The value of x in the main() = %d", x);
int x = 2;
printf("\n The value of local variable x in the main() = %d", x);
print();
return 0;
}
void print()
{
printf("\n The value of x in the print() = %d", x);
}
Output
The value of x in the main() = 10
The value of local variable x in the main() = 2
The value of x in the print() = 10
From the code we see that local variables overwrite the value of global variables. In big programs use of global variables is not recommended until it is very important to use them because there is a big risk of confusing them with any local variables of the same name.
Note: Functions are considered to be self-contained and independent modules. So they need to be isolated from the rest of the code, but using global variables goes against this idea behind creating independent functions.
4.8.4 File Scope
When a global variable is accessible until the end of the file, the variable is said to have file scope. To allow a variable to have file scope, declare that variable with the static keyword before specifying its data type:
static int x = 10;
A global static variable can be used anywhere from the file in which it is declared but it is not accessible by any other file. Such variables are useful when the programmer writes his own header files.
4.9 STORAGE CLASSES
Storage class defines the scope (visibility) and lifetime of variables and/or functions declared within a C program. In addition to this, the storage class gives the following information about the variable or the function.
The storage class of a function or a variable determines the part of memory where storage space will be allocated for that variable or function (whether the variable/function will be stored in a register or in RAM).
It specifies how long the storage allocation will continue to exist for that variable or function.
It specifies the scope of the variable or function, i.e., the storage class indicates the part of the C program in which the variable name is visible or the part in which it is accessible. In other words, whether the variable/function can be referenced throughout the program or only within the function, block, or source file where it has been defined.
It specifies whether the variable or function has internal, or no linkage.
It specifies whether the variable will be automatically initialized to zero or to any indeterminate value.
C supports four storage classes: automatic, register, external, and static. The general syntax for specifying the storage class of a variable can be given as:
The auto storage class specifier is used to explicitly declare a variable with automatic storage. It is the default storage class for variables declared inside a block. For example, if we write
auto int x;
then x is an integer that has automatic storage. It is deleted when the block in which x is declared is exited.
The auto storage class can be used to declare variables in a block or the names of function parameters. However, since the variable names or names of function parameters by default have automatic storage, the auto storage class specifier is therefore treated as redundant while declaring data.
Important things to remember about variables declared with auto storage class include:
All local variables belong to automatic storage class by default.
They should be declared at the start of the program block, right after the opening curly bracket {.
Memory for the variable is automatically allocated upon entry to a block and freed automatically upon exit from that block.
The scope of the variable is local to the block in which it is declared. These variables may be declared within a nested block.
Every time the block (in which the automatic variable is declared) is entered, the variable is initialized with the values declared.
The auto variables are stored in the primary memory of the computer.
If auto variables are not initialized at the time of declaration, then they contain some garbage value.
The following code uses an auto integer that is local to the function in which it is defined.
#include <stdio.h>
void func1()
{
int a=10;
printf("\n a = %d", a);
// auto integer local to func1()
}
void func2()
{
int a=20;
printf("\n a = %d", a);
// auto integer local to func2()
}
void main()
{
int a=30; // auto integer local to main()
func1();
func2();
printf("\n a = %d", a);
}
Output
a = 10
a = 20
a = 30
4.9.2 register Storage Class
When a variable is declared using register as its storage class, it is stored in a CPU register instead of RAM. Since the maximum size of the variable is equal to the register size. One drawback of using a register variable is that they cannot be operated using the unary '&' operator because it does not have a memory location associated with it. A register variable is declared in the following manner:
register int x;
Register variables are used when quick access to the variable is needed. It is not always necessary that the register variable will be stored in the register. Rather, the register variable might be stored in a register depending on the hardware and implementation restrictions.
Hence, programmers can only suggest to the compiler to store those variables in the registers which are used repeatedly or whose access times are critical. However, for the compiler, it is not an obligation to always accept such requests. In case the compiler rejects the request to store the variable in the register, the variable is treated as having the storage class specifier auto.
Like auto variables, register variables also have automatic storage duration. That is, each time a block is entered, the register variables defined in that block are accessible and the moment that block is exited, the variables become no longer accessible for use. Now let us have a look at the following code that uses a register variable.
#include <stdio.h>
int exp(int a, int b);
int main()
{
int a=3, b=5, res;
res = exp(a, b);
printf("\n %d to the power of %d = %d", a, b, res);
return 0;
}
int exp(int a, int b)
{
register int res=1;
int i;
for(i=1;i<=b;i++)
res = res*a;
return res;
}
Output
3 to the power of 5 = 243
4.9.3 extern Storage Class
A large C program can be broken down into smaller programs. When these smaller programs are compiled, they are joined together to form a large program. However, these smaller programs may need to share certain variables for processing. For such situations C language provides an external storage class that is specified using the keyword extern.
The extern storage class is used to give a reference of a global variable that is visible to all the program files. Such global variables are declared like any other variable in one of the program files. When there are multiple files in a program and you need to use a particular function or variable in a file apart from which it is declared, then use the extern keyword. To declare a variable x as extern write,
extern int x;
External variables may be declared outside any function in a source code file as any other variable is declared. But usually external variables are declared and defined at the beginning of a source file.
Memory is allocated for external variables when the program begins execution, and remains allocated until the program terminates. External variables may be initialized while they are declared. However, the initializer must be a constant expression. The compiler will initialize its value only once during the compiler time. In case the extern variable is not initialized, it will be initialized to zero by default.
External variables have global scope, i.e., these variables are visible and accessible from all the functions in the program. However, if any function has a local variable with the same name and type as that of the global or extern variable, then references to the name will access the local variable rather than the extern variable. Hence extern variables are overwritten by local variables.
Let us now write a program in which we will use the extern keyword.
// FILE 1.C
#include <stdio.h>
#include <FILE2.C>
// Programmer's own header file
int x;
void print(void);
int main()
{
x = 10;
printf("\n x in FILE1 = %d", x);
print();
return 0;
}
// END OF FILE1.C
// FILE2.C
#include <stdio.h>
extern int x;
void print()
{
printf("\n x in FILE 2 = %d", x);
}
main()
{
// Statements
}
// END OF FILE2.C
Output
x in FILE1 = 10
x in FILE2 = 10
In the program, we have used two files—File1 and File2. File1 has declared a global variable x. File1 also includes File2 which has a print function that uses the external variable x to print its value on the screen.
Note: The extern specifier tells the compiler that the variable has already been declared elsewhere and therefore it should not allocate storage space for that variable again. During compilation of the program, the linker will automatically resolve the reference problem.
In a multi-file program, the global variable must be declared only once (in any one of the files) without using the extern keyword. This is because otherwise the linker will have a conflict as to which variable to use and therefore in such a situation it raises a warning message.
4.9.4 static Storage Class
While auto is the default storage class for all local variables, static is the default storage class for all global variables. Static variables have a lifetime over the entire program, i.e., memory for the static variables is allocated when the program begins running and is freed when the program terminates. To declare an integer x as static, write
static int x = 10;
Here x is a local static variable. Static local variables when defined within a function are initialized at the runtime. The difference between an auto variable and a static variable when defined within a function is that the static variable is not re-initialized when the function is called again and again. It is initialized just once and further calls of the function share the value of the static variable. Hence, the static variable inside a function retains its value during various calls.
When a static variable is not explicitly initialized by the programmer, then it is automatically initialized to zero when memory is allocated for it. Although static automatic variables exist even after the block in which they are defined terminates, their scope is local to the block in which they are defined.
Static storage class can be specified for auto as well as extern variables. For example we can write,
static extern int x;
When we declare a variable as extern static variable, then that variable is accessible from all the functions in this source file.
Note:static variables can be initialized while they are being declared. But this initialization is done only once at the compile time when memory is being allocated for the static variable. Also the value with which the static variable is initialized must be a constant expression.
Look at the following code which clearly differentiates between a static variable and a normal variable.
#include <stdio.h>
void print(void);
int main()
{
printf("\n First call of print()");
print();
printf("\n\n Second call of print()");
print();
printf("\n\n Third call of print()");
print();
return 0;
}
void print()
{
static int x;
int y = 0;
printf("\n Static integer variable, x = %d", x);
printf("\n Integer variable, y = %d", y);
x++;
y++;
}
Output
First call of print()
Static integer variable, x = 0
Integer variable, y = 0
Second call of print()
Static integer variable, x = 1
Integer variable, y = 0
Third call of print()
Static integer variable, x = 2
Integer variable, y = 0
4.9.5 Comparison of Storage Classes
Table 4.2 compares the key features of all the storage classes.
Table 4.2 Comparison of storage classes
FEATURE
auto
extern
register
static
Accessibility
Accessible within the function or block in which it is declared.
Accessible within all program files that are a part of the program.
Accessible within the function or block in which it is declared.
Local: Accessible within the function or block in which it is declared. Global: Accessible within the program in which it is declared.
Storage
Main memory
Main memory
CPU register
Main memory
Existence
Exists when the function or block in which it is declared is entered. Ceases to exist when the control returns from the function or the block in which it was declared.
Exists throughout the execution of the program.
Exists when the function or block in which it is declared is entered. Ceases to exist when the control returns from the function or the block in which it was declared.
Local: Retains value between function calls or block entries. Global: Preserves value in program files.
Default value
Garbage
Zero
Garbage
Zero
4.10 RECURSIVE FUNCTIONS
A recursive function is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Every recursive solution has two major cases:
Base case, in which the problem is simple enough to be solved directly without making any further calls to the same function.
Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub-parts.
Therefore, recursion is defining a large and complex problem in terms of smaller and more easily solvable problems. In recursive function, a complex problem is defined in terms of simpler problems and the simplest problem is given explicitly.
To understand recursive functions, let us take an example of calculating factorial of a number. To calculate n!, we multiply the number with factorial of the number that is 1 less than that number. In other words,
n! = n × (n-1)!
Let us say we need to find the value of 5!.
5! = 5 × 4 × 3 × 2 × 1
= 120
This can be written as
5! = 5 × 4!, where 4! = 4 × 3!
Therefore,
5! = 5 × 4 × 3!
Similarly, we can also write,
5! = 5 × 4 × 3 × 2!
Expanding further
5! = 5 × 4 × 3 × 2 × 1!
We know, 1! = 1
Therefore, the series of problems and solutions can be given as shown in Figure 4.6.
Figure 4.6 Recursive factorial function
PROBLEM
SOLUTION
5!
5 × 4 × 3 × 2 × 1!
= 5 × 4!
= 5 × 4 × 3 × 2 × 1
= 5 × 4 × 3!
= 5 × 4 × 3 × 2
= 5 × 4 × 3 × 2!
= 5 × 4 × 6
= 5 × 4 × 3 × 2 × 1!
= 5 × 24
= 120
Now if you look at the problem carefully, you can see that we can write a recursive function to calculate the factorial of a number. Every recursive function must have a base case and a recursive case. For the factorial function,
Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as
factorial(n) = n × factorial(n-1)
Programming Tip: Every recursive function must have at least one base case. Otherwise, the recursive function will generate an infinite sequence of calls thereby resulting in an error condition known as an infinite stack.
Look at the following code which calculates the factorial of a number recursively.
#include <stdio.h>
int Fact(int);
int main()
{
int num, factorial;
printf("\n Enter the number: ");
scanf("%d", &num);
factorial = Fact(num);
printf("\n Factorial of %d = %d", num, factorial);
return 0;
}
int Fact(int n)
{
if(n==1)
return 1;
else
return (n * Fact(n-1));
}