[prog] c types confusion

Alice Moomlyn alice_moomlyn at yahoo.com
Wed Mar 24 05:06:53 EST 2004


#include <stdio.h>

/* This program does not do what I expect it to do.

   Firstly, I would have expected signed int
   to wrap at 2^15, rather than 2^31.

   Secondly, I would have expected unsigned int
   to hold 2^31 quite confortable.
   But instead it wrapped to a negative number.
   Strange.

   Thirdly I would have expected float to start
   losing precision well before 2^31.
   But this didn't happen!

   Am I misunderstanding something?

 */

int main()
{
   int MyInt = 1;
   unsigned int MyUnsignedInt = 1;
   float MyFloat = 1.0;

   printf("\nAn int is \t\t %d bytes", sizeof(int));
   printf("\nAn unsigned int is \t %d bytes",
sizeof(unsigned int));
   printf("\nA float is \t\t %d bytes",
sizeof(float));

   int top = 8*sizeof(int) - 1;
   int counter = 0;

   while (counter <= top)
   {
       printf("\ncounter: %d\n", counter);
       printf("int: %d ", MyInt);
       printf("unsigned int: %d ", MyUnsignedInt);
       printf("float: %f \n", MyFloat);

       MyInt *= 2;
       MyUnsignedInt *= 2;
       MyFloat *= 2.0;

       counter++;
   };

   return 0;
}

/* P.S. Thankyou dominik for your last reply. */

=====
"the only way to learn how to be clever is to say stupid things" - anon

__________________________________
Do you Yahoo!?
Yahoo! Finance Tax Center - File online. File on time.
http://taxes.yahoo.com/filing.html


More information about the Programming mailing list