Monday, February 5, 2018

Coding using keywords- part 5 (register)

register keyword is used to access directly the CPU; by using this keyword before any data type the variable will be set inside a register's CPU directly. Let's see the CPU structure briefly:




C program example:


  1. #include <stdio.h>  
  2.    
  3. int main () {  
  4.     register int a=5;  
  5.     printf("The value of a is %d", a);
  6.     return 0;  
  7. }  

In this example by using register keyword, you can access the data quickly. When using this keyword you're asking the compiler to save the variable a in the processor's register. I should also mention that printf is also used to output on the terminal and %d is used to set a decimal in this place (a because it's an integer number).

You can also add address to the memory location by using a pointer variable. Here comes an example:

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.      int i = 10;  
  5.      register int *a = &i;  
  6.      printf("%d", *a);  
  7.      getchar();  
  8.      return 0;  
  9. }  

After saving the value of i inside the CPU's register, a pointer is set to get the address of the memory location where the variable i is set. For instance, when you run the program you'll see the address referenced by the pointer a.

No comments:

Post a Comment