Register keyword in C
The variables which are most frequently used in a program can be put in registers using 'register' keyword because register are faster than memory to access..The keyword 'register' tells compiler to store the variable in register instead of memory.Its compiler choice to put it in register or not.But mostly when compiler do optimizations then they put the variables in registers.
When we store variables in a register and not in memory we cannot use & operator with variables because we cannot access the address of register.Using & operator with register variable will throw error by the compiler.
int main()
{
register int j=10;
int *p=&j;
printf("%d",*p);
getch();
}
The above program will throw error as we are accessing address of register variable j.Now suppose we make pointer variable register instead of j what will happen now? will program run successfully or throw error?
int main()
{
int j=10;
register int *p=&j;
printf("%d",*p);
getch();
}
Obviously the above program will not throw any error because a register can have a address of memory location.
Also register are storage class and C doesnot allow multiple storage class specifiers for variable so they cannot be used with static keyword.
int main()
{
int j=10;
register static int *p=&j;
printf("%d",*p);
getch();
}
The above program will throw error.
When we store variables in a register and not in memory we cannot use & operator with variables because we cannot access the address of register.Using & operator with register variable will throw error by the compiler.
int main()
{
register int j=10;
int *p=&j;
printf("%d",*p);
getch();
}
The above program will throw error as we are accessing address of register variable j.Now suppose we make pointer variable register instead of j what will happen now? will program run successfully or throw error?
int main()
{
int j=10;
register int *p=&j;
printf("%d",*p);
getch();
}
Obviously the above program will not throw any error because a register can have a address of memory location.
Also register are storage class and C doesnot allow multiple storage class specifiers for variable so they cannot be used with static keyword.
int main()
{
int j=10;
register static int *p=&j;
printf("%d",*p);
getch();
}
The above program will throw error.
Comments
Post a Comment