Explaining Register variables in C with examples

A register is a small data storage location inside the processor, most of the time registers are used to hold memory locations, arithmetic/logical instructions etc. Registers can hold up to 64-bit data depending upon the processor.

Register memory takes very few clock cycles to access so it is very fast as compared to the main memory.

Also Read: Macros in C with examples C Tutorials

The «register» keyword in c

In c programming, the keyword register is used to ask the compiler to store the data inside the variable into a register but it’s totally up to the compiler whether to store that data into a register or not because most of the modern day compilers use multiple optimisation techniques so the compiler itself put the “worthy” variables inside the register.

Why use «register» keyword?

There may be some variables in your program which are used very much frequently, so they can be stored inside a register so that the processor needs less amount of cycles to access them but most of the modern day compilers are smart enough to do this task automatically.

Simple Example based on register variables in C

#include<stdio.h>  Int main(){  register int x = 10; printf("\%d",x); return 0; }

The above code will produce the following output.


Let’s try something different, in the next example, we will try to print the address of the register.

#include<stdio.h>  Int main(){  register int x = 10; int *a = &x; printf("\%d",*a); return 0; } 

When you will execute the above code it may give you an error it is because registers don’t have any address because registers do not reside inside the main memory they are identified using their names. Eg: PC, ECX.

When to use register variables

The answer is pretty simple when you consider yourself smarter than the compiler wink, so basically you can tell your compiler how to optimise the code by using the register variables but most of the time compiler ignore the register keyword and optimise the code itself.

Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий