Tuesday, 1 January 2013

C/C++ Puzzles: PART - 14

Beware of the Return Type of Functions

  In C and C++ there is a rich set of library functions available. But we must be very careful about the return type of functions. For example consider the program given below. 

#include<stdio.h>
int main()
{
   int i=-1;
   if(i<sizeof(int))
   {
       printf("\nThis is the expected Output, since sizeof(int) is 4\n");
   }
   else
   {
       printf("\nThis is the actual Output\n");
   }
}


The expected Output is the message "This is the expected Output, since sizeof(int) is 4", but the actual Output is the message "This is the actual Output".

The Figure Below Shows the Output

 What is the reason? The return type of sizeof is unsigned int. Therefor the value of integer i is also considered as an unsigned integer. Thus the value of i becomes a large positive integer (4294967295) which is greater than 4. 

No comments:

Post a Comment