top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can we declare a variable as both constant and volatile? [CLOSED]

+6 votes
292 views
Can we declare a variable as both constant and volatile? [CLOSED]
This question has an answer at: Can a variable be both constant and volatile?
posted Dec 3, 2013 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Const means the program cannot modify the value volatile means the value may be arbitrarily modified outside the program. the two are separate and not mutually exclusive.
Use them together, for instance, in the case of reading a hardware status register. Const prevents the value from being stomped on, while volatile tells the compiler that this value can be changed at any time external to the program.
This const volatile<type><variable name> will thus satisfy both requirements and prevent an optimizing compiler from incorrectly optimizing the code, that it would do if only "const" were used.

1 Answer

0 votes

Doing some cheating, picking from previous Question....

Answer is Yes. The const modifier means that this code cannot change the value of the variable, volatile still means that compiler cannot optimize or reorder. Both can appear in any order i.e. constant volatile or volatile constant.

answer Dec 3, 2013 by Meenal Mishra
...