Thursday, November 7, 2013

Removing warning from the program

Now, type the following code:

#include <stdio.h>
#include <conio.h>
main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
}
Save the program. Compile it and observe the compiling dialog box, it display 1 warning. Press Enter and observe the message window located at the bottom of the window. This window appears time by time when you make mistake your program or after compiling, you may press Enter to see the warning message)

Warning PROG6.C 9: Function should return a value.

What does this warning indicates? And how we can get rid of this warning? Cool…

Removing warning from the program
In C by default every user defined function returns an integer value to its caller function. Remember main() is also one of the user defined function and so it also return some value to its caller (i.e. Operating System). And this is the main reason for this warning.
     1)   Adding void keyword before main().
     2)   Adding return statement at the end of program.

Now we are going to write modified version of the above program.

/* Removing warniong from the program. Method #1 */
#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
}

The keyword void before main() indicates that the function main() is not going to return any value to its caller (i.e. OS).

/* Removing warniong from the program. Method #2 */
#include <stdio.h>
#include <conio.h>
main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
    return(0);

}

The keyword return is used to terminate the function and return a value to its caller. The return statement may OR may not include an expression.

The general form of return statement is:
return(expression);
Some valid return statement examples are:
return;
return(0);
return 0;

Note: A nonzero value returned by the return statement tells the OS that an error has occurred.

No comments:

Post a Comment