Sunday, October 30, 2011

One Dicey Issue of Loop Control Structure in C programing

Consider the following function calls:

#include <conio.h>
clrscr ( ) ;
gotoxy ( 10, 20 ) ;
ch = getch ( a ) ;

Here we are calling three standard library functions. Whenever we call the library functions we must write their prototype before making the call. This helps the compiler in checking whether the values being passed and returned are as per the prototype declaration. But since we don’t define the library functions (we merely call them) we may not know the prototypes of library functions. Hence when the library of functions is provided a set of ‘.h’ files is also provided. These files contain the prototypes of library functions. But why multiple files? Because the library functions are divided into different groups and one file is provided for each group. For example, prototypes of all input/output functions are provided in the file ‘stdio.h’, prototypes of all mathematical functions are provided in the file ‘math.h’, etc.
On compilation of the above code the compiler reports all errors due to the mismatch between parameters in function call and their corresponding prototypes declared in the file ‘conio.h’. You can even open this file and look at the prototypes. They would appear as shown below:

void clrscr( ) ;
void gotoxy ( int, int ) ;
int getch( ) ;

Now consider the following function calls:

#include <stdio.h>
int i = 10, j = 20 ;
printf ( "%d %d %d ", i, j ) ;
printf ( "%d", i, j ) ;

The above functions get successfully compiled even though there is a mismatch in the format specifiers and the variables in the list. This is because printf( ) accepts variable number of arguments (sometimes 2 arguments, sometimes 3 arguments, etc.), and even with the mismatch above the call still matches with the prototype of printf( ) present in ‘stdio.h’. At run-time when the first printf( ) is executed, since there is no variable matching with the last specifier %d, a garbage integer gets printed. Similarly, in the second printf( ) since the format specifier for j has not been mentioned its value does not get printed.

3 comments: