Feb 5, 2020

Multi-file programs in C



           Unit IV-multi-file programs.


       File Inclusion
The preprocessor command for file inclusion looks like this:
#include "filename"
and it simply causes the entire contents of filename to be inserted into the source code at that point in the program. Of course this presumes that the file being included is existing. When and why this feature is used? It can be used in two cases:
(a)                   If we have a very large program, the code is best divided into several different files, each containing a set of related functions. It is a good programming practice to keep different sections of a large program separate. These files are #included at the beginning of main program file.

(b)                  There are some functions and some macro definitions that we need almost in all programs that we write. These commonly needed functions and macro definitions can be stored in a file, and that file can be included in every program we write, which would add all the statements in this file to our program as if we have typed them in. It is common for the files that are to be included to have a .h extension.

Actually there exist two ways to write #include statement. These are:
#include "filename"
#include <filename>

The meaning of each of these forms is given below:


#include "goto.c"

This command would look for the file goto.c in the current directory as well as the specified list of directories as mentioned in the include search path that might have been set up.

#include <goto.c>
This command would look for the file goto.c in the specified list of directories only.

Scope and lifetime of variables in functions.

               Unit IV (Contd…..)

            scope and lifetime of variables in functions.          


          Scope Rules

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places where variables can be declared in C programming language:
·        Inside a function or a block which is called local variables,
·        Outside of all functions which is called global variables.
·        In the definition of function parameters which is called formal parameters.
           Let us explain what are local and global variables and formal parameters.

           Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Here all the variables a, b and c are local to main() function.

#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

          Global Variables

Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}

A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example:

#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}

         When the above code is compiled and executed, it produces the following result:

value of g = 10

          Formal Parameters

Function parameters, so called formal parameters, are treated as local variables within that function and they will take preference over the global variables. Following is an example:

#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result:

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

          Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows:



Data Type
Initial Default Value
int
0
char
'\0'
float
0
double
0
pointer
NULL

It is a good programming practice to initialize variables properly otherwise, your program may produce unexpected results because uninitialized variables will take some garbage value already available at its memory location.

Type of User-defined Functions in C, Recursion


                Unit IV (Contd…..)


              Various categories of functions, Nesting of functions and recursion.


            Type of User-defined Functions in C

There can be 4 different types of user-defined functions, they are:

·        Function with no arguments and no return value
·        Function with no arguments and a return value
·        Function with arguments and no return value
·        Function with arguments and a return value

           Below, we will discuss about all these types, along with program examples.

          Function with no arguments and no return value

Such functions can either be used to display information or they are completely dependent on user inputs.
Below is an example of a function, which takes 2 numbers as input from user, and display which is the greater number.
 
#include<stdio.h>
 
void greatNum();       // function declaration
 
int main()
{
    greatNum();        // function call
    return 0;
}
 
void greatNum()        // function definition
{
    int i, j;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    if(i > j) {
        printf("The greater number is: %d", i);
    }
    else {
        printf("The greater number is: %d", j);
    }
}

           Function with no arguments and a return value

We have modified the above example to make the function greatNum() return the number which is greater amongst the 2 input numbers.
#include<stdio.h>
 
int greatNum();       // function declaration
 
int main()
{
    int result;
    result = greatNum();        // function call
    printf("The greater number is: %d", result);
    return 0;
}
 
int greatNum()        // function definition
{
    int i, j, greaterNum;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    if(i > j) {
        greaterNum = i;
    }
    else {
        greaterNum = j;
    }
    // returning the result
    return greaterNum;
}

             Function with arguments and no return value

We are using the same function as example again and again, to demonstrate that to solve a problem there can be many different ways.
This time, we have modified the above example to make the function greatNum() take two int values as arguments, but it will not be returning anything.

#include<stdio.h>

void greatNum(int a, int b);       // function declaration

int main()
{
    int i, j;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    greatNum(i, j);        // function call
    return 0;
}

void greatNum(int x, int y)        // function definition
{
    if(x > y) {
        printf("The greater number is: %d", x);
    }
    else {
        printf("The greater number is: %d", y);
    }
}

           Function with arguments and a return value

This is the best type, as this makes the function completely independent of inputs and outputs, and only the logic is defined inside the function body.

#include<stdio.h>

int greatNum(int a, int b);       // function declaration

int main()
{
    int i, j, result;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    result = greatNum(i, j); // function call
    printf("The greater number is: %d", result);
    return 0;
}

int greatNum(int x, int y)        // function definition
{
    if(x > y) {
        return x;
    }
    else {
        return y;
    }
}

          Nested functions in C

In some applications, we have seen that some functions are declared inside another function. This is sometimes known as nested function, but actually this is not the nested function. This is called the lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct memory location of inner function.
Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C there are two nested scopes the local and the global. So nested function has some limited use. If we want to create nested function like below, it will generate error. 

          What is Recursion?

Recursion is a special way of nesting functions, where a function calls itself inside it. We must have certain conditions in the function to break out of the recursion, otherwise recursion will occur infinite times.

          Example: Factorial of a number using Recursion

#include<stdio.h>

int factorial(int x);       /*declaring the function*/

void main()
{
    int a, b;
   
    printf("Enter a number...");
    scanf("%d", &a);
    b = factorial(a);       /*calling the function named factorial*/
    printf("%d", b);
}

int factorial(int x)          /*defining the function*/
{
    int r = 1;
    if(x == 1)
        return 1;
    else
        r = x*factorial(x-1);       /*recursion, since the function calls itself*/
   
    return r;
}