Explaining Register variables in C with examples

by

Posted on 17 August 2018

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.

10

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.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement