Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile const int meaning in C?

Tags:

c

I am reading a book on C. It mentions a concept which does not make sense to me. What I know is that the compiler sometimes optimises code by removing variables which it feels would not affect an expression. So if we specify volatile to a variable, it does not remove this variable from any expression.

So the book introduces something like this:

volatile const int a = 1;

The explaination is only a couple of lines, none of which makes sense to me. Can somebody please explain why would be there a need of such a variable?

PS: I understand the concept of volatile, what I dont understand is the concept of volatile const.

like image 741
Cool_Coder Avatar asked Dec 03 '13 14:12

Cool_Coder


People also ask

What is const volatile int?

const int temp; is a variable stored in (read-ony)FLASH, initialized to 0 at compiler time, cached values may be used. volatile int temp; is a variable stored in RAM, initialized to 0 at startup (cstart), cached values will NOT be used.

What does volatile int mean in C?

Introduction to Volatile in C. A volatile keyword in C is nothing but a qualifier that is used by the programmer when they declare a variable in source code. It is used to inform the compiler that the variable value can be changed any time without any task given by the source code.

What is volatile data type in C?

C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.

Can we use const with volatile?

Yes a C++ variable be both const and volatile. It is used in situations like a read-only hardware register, or an output of another thread. Volatile means it may be changed by something external to the current thread and Const means that you do not write to it (in that program that is using the const declaration).


2 Answers

A volatile const variable is one whose value may change due to external influences, and which cannot be written to.

like image 114
Graham Borland Avatar answered Nov 15 '22 05:11

Graham Borland


Volatile const means value cannot be changed programmatically but value can be changed indirectly, for eg if the variable is mapped to device register, then value can be modified by the device.

like image 41
rajeshsam Avatar answered Nov 15 '22 04:11

rajeshsam