Number data types
 

Number data types

  • the number data types are:

       
          Integer                 Floating point
         -------------          ------------------   
          char  (1 byte)          float  (4 bytes) 
          short (2 bytes)	    double (8 bytes)
          int   (4 bytes)
          long  (8 bytes)
      

    char is like the byte type in Java

    I.e.: these are the data types that you used to store an integer (whole) or floating point number

Java has automatic casting between 2 number data types when it is safe (= no loss of accuracy)
 

  • Java allows automatic casting when it is safe (= no loss of accuracy):

         short x = 5;
         int   y;
      
         y = x;     // Safe to cast short to int  
      

  • Java disallows automatic casting when it is unsafe:

         int   x = 5;
         short y;
      
         y = x;  // Need explicit casting in Java ! 
      

DEMO: demo/C/set1/javaCasting.java

C will always allow automatic casting between any 2 number data types
 

  • In C, the C compiler will always allow automatic casting - even when it is unsafe:

       #include <stdio.h>
      
       int main(int argc, char *argv[])             
       {
         int   x = 5;
         short y;
      
         y = x;  // C allows it !!
      
         printf("%d\n", y);
       }    
      

DEMO: demo/C/set1/c-casting.c

Try other data types, like casting from double to a short !

We say that: "C is a weakly typed programming language" for the lack of type checking

Make the C compiler print out warning messages on dangerous casting operations

 

  • The C compiler option -Wconversion will print out warning messages when an assignment uses a wider data tye:

       gcc -Wconversion casting01a.c

    (-W stands for warning)

DEMO: demo/C/set1/c-casting.c --- Compile with: gcc -Wconversion c-casting.c

Note:   a warning from the C compiler is not a fatal error --- but, you should fix it