Review: background information on compilers
 

  • Review:

    • Information = data + context

    • data = the binary number stored in a variable

    • context = the data type of a variable

  • Background information:

    • In order to translate statements that contains variables - such as:

         x = y + z;
      

      the compiler must know the data type of every variable in the expression

I can now explain the reason to you...

How does a compiler translate statements with variables

  • If a variable y used to computation:

      x =  y + z 
    

    has the data type byte, the compiler must translate the statement to:

         movw   r0, #:lower16:y
         movt   r0, #:lower16:y
    
         ldrsb  r1, [r0]
    

    to fetch the value from the byte typed variable

(You saw in the previous slides what can go wrong if you don't !)

How does a compiler translate statements with variables

  • On the other hand, if a variable y used to computation:

      x =  y + z 
    

    has the data type short, the compiler must translate the statement to:

         movw   r0, #:lower16:y
         movt   r0, #:lower16:y
    
         ldrsh  r1, [r0]
    

    to fetch the value from the short typed variable

(You saw in the previous slides what can go wrong if you don't !)

How does a compiler translate statements with variables

  • But, if a variable y used to computation:

      x =  y + z 
    

    has the data type int, the compiler must translate the statement to:

         movw   r0, #:lower16:y
         movt   r0, #:lower16:y
    
         ldr    r1, [r0]
    

    to fetch the value from the int typed variable

(You saw in the previous slides what can go wrong if you don't !)

Reason why you need to declare global variables in C

  • This C program cannot be compiled correctly:

      #include <stdio.h>
    
    
    
      int main( )
      {
         printf("%d\n", x); // Use variable x before it was defined
      }
    
      int x = 1234;         // Definition of variable x 
      

    because the data type of the variable x is not known when x was used in the printf( ) statement.

    Therefore:

    • The C compiler cannot choose the correct load instruction

Reason why you need to declare global variables in C

  • The declaration of the variable x will solve the problem:

      #include <stdio.h>
    
      extern int x;
    
      int main( )
      {
         printf("%d\n", x); // Statement can now be translated     
      }                     // correctly                      
    
      int x = 1234;         // Definition of variable x 
      

    Now the data type of the variable x is known (int) when x was used.

    Therefore:

    • The C compiler can choose the correct load instruction:   ldr

OLD DEMO:   /home/cs255001/demo/c/set1/c-1pass.c (edit it)