void main ( ) and int main ( )


Remember I said that void main ( ) is the same as writing :  
int main ( )
{
.................   
//program code
return 0;
}


I'll now show you a little benefit of using int main( ). Consider the following program : 

# include<iostream.h>
int main ( )
{
int a;
cout<<"Enter a value :";
cin>>a;
if (a= =1)
{
cout<<"You typed 1";
return 1;
}
cout<<"This line is displayed if you typed a value other than 1";
return 0;
}

What do you think happens when the user types 1 as the value of test?

Simple; since test is equal to 1, the compiler will go into the body of if. It will display You typed 1 on the screen. Then the compiler will return a value of 1. Generally a return value of a non-zero number is used when errors are encountered. You can't use this return value anywhere else. In other functions (functions other than main), you can make use of the return value. A return value of 0 indicates a normally terminated program. After returning the value, the program exits. This is the point to be noted. Which means that the compiler will not even read the remaining few lines and hence nothing else will display on the screen. The compiler will quit once an integer has been returned to main.

On the other hand if you type anything other than 1 for test, the compiler will skip the if body, display the last statement and then return 0. The program gets terminated. Learn more in the next section.


Go on to the next section on Which one is better int main or void main?

or go back to Contents page 2.


Copyright © 2003 Sethu Subramanian All rights reserved.