C Programming

How to Use register Keyword in C

In C programming, keywords are reserved words with specific meanings and functions. One of these keywords is “register”, which is a storing class specifier that instructs the compiler to keep a particular variable in a register on the CPU rather than memory. This article will provide an overview of the register keyword in C and its usage.

What is the register Keyword in C

The keyword “register” in C is a storing class specifier that may be employed to tell the interpreter that a specific variable needs to be kept in a register on the CPU rather than storage. Registers are much quicker than memory, and the CPU’s accessibility time is also much shorter. As a result, we use the keyword “register” which is mainly used in the program. In simple terms, the register keyword restricts the compiler to store the value in a register on the CPU to ensure it can be retrieved quickly. However, it is up to the compiler to place that value in a CPU register or ram.

Scope of the register Keyword

In C programming, the scope of the register keyword is local, which means it can only be accessed within the local functions where it is defined. Its execution ends when the block is terminated where it is defined.

Syntax

The following is the syntax to use the register keyword in C programming:

register <datatype> <variable_name>;

For example, to declare a register of int data type, the following code is used:

register int num;

Simple Example of Register Keyword in C

The following is a simple example of C code using the register.

#include<stdio.h>

int main() {

  int num= 10;
 
  register int *p = &num;

printf("Pointer value is: %d", *p);

  return 0;

}

The above program declares a variable num with the value 10. It also declares a pointer p using the register keyword, which suggests to the compiler that p should be stored in a register for faster access. p is initialized to point to the memory address of num. The program then prints the value of the memory location pointed to by p using the printf() function. Finally, the program returns 0 to indicate successful execution.

Output

Conclusion

The register in C is a keyword that directs the compiler to determine that a specific variable should be kept in a CPU register rather than memory. The above article shows a detail guided about the register keyword, its declaration, and its use in the C programming language.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.