The assignment statement in C

  • The assignment statement in C has the same syntax and meaning as Java:

       var = expression ;
    
          (1) Evaluate the expression on the RHS
          (2) Convert if necessary to the correct data type
          (3) Assign the result to the variable on the LHS 

  • Warning:

      • C will always perform the conversion automatically for number data types

      • Even when the RHS value is a wider data type than the LHS variable !

An assignment statement example to hightlight the difference in C and Java

  • The following assignment statement will compile and run correctly in C:

    #include <stdio.h>
    
    int main( int argc, char* argv[] )
    {
       double r = 1.0;
       int    integralAreaOfCircle;
    
       integralAreaOfCircle = 3.14 * r * r;  // Assign double value 
                                             // to an int typed variable
    
       printf("Integral area of circle with radius %f = %d\n",
                    r, integralAreaOfCircle);
    }   

  • This assignment statement will cause compile error in Java...

    (Java requires a casting operator...)

DEMO: demo/C/set1/casting3.c

An assignment statement example to hightlight the difference in C and Java

  • The same assignment statement will cause compile error in Java:

    public class casting3
    {
       public static void main( String[] args )
       {
          double r = 1.0;
          int    integralAreaOfCircle;
    
          integralAreaOfCircle = 3.14 * r * r;  // Assign double value 
                                                // to an int typed variable
    
          System.out.printf("Integral area of circle with radius %f = %d\n",
                              r, integralAreaOfCircle);
       }
    }   

    (Java requires a casting operator...)

DEMO: demo/C/set1/casting3.java