Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would a "register volatile int i" behave in C?

Tags:

c

volatile

I understand that a register keyword will assign a register for computing the value and a volatile keyword will read the value from the memory every time when we perform some computation on the variable and basically not optimize the code. So, if a variable is assigned both these keywords then, would it mean that it would essentially be volatile itself? I cannot understand the behavior by writing a sample code. Can anybody shed some light?

like image 450
knightofhorizon Avatar asked Sep 24 '12 15:09

knightofhorizon


1 Answers

In C, the register storage class behaves exactly as the auto storage class, except that the implementation is required (per 5.1.1.3) to issue a diagnostic if the program attempts to take or use the address of the object (6.5.3.2, 6.7.1). The use of register as an optimisation hint to the compiler is generally pointless, as a compiler smart enough to exploit the non-stored quality of the object is certainly smart enough to track which objects could be declared register; instead, it should be understood as a code quality check that the programmer is not inadvertently destroying optimisation opportunities by taking the address of the object.

In other words, removing all instances of the register keyword from a valid program has no effect on the program's semantics; it is similar in this regard to static_assert.

The volatile type qualifier indicates that accesses to (reads from and writes to) the object are considered side effects and cannot be optimised away. For an object that does not exist in a defined location memory (i.e., one having the register storage class), this would be most useful in performance testing:

start = time();
for (multiple loops)
    register volatile int result = test_function();
stop = time();
elapsed = stop - start;
like image 55
ecatmur Avatar answered Oct 03 '22 10:10

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!