Question about the volatile keyword

I know that using the keyword volatile

volatile int k=7; 

we are hinting to the compiler that a variable can be changed at any time, but what about a simple one int k=7? Can we change it at any time because it is not permanent? What else?

+5
source share
6 answers

It is used when programming at a low level with interrupts, etc. primarily

volatile int count;

void test()
{
   while(count< 100) 
   {
        // do nothing
   }
}

//
// Interrupt function called by the hardware automatically at intervals
//
void interrupt()
{
    count = count + 1;
}

if you do not declare the variable as volatile, the compiler will probably notice that the counter cannot change during the while loop, and therefore will not worry about actually reading the value each time from memory so that it never exits the loop.

volatile, , , ...

- .

, "" . , , , , . volatile , , , , , , , .

, .

: , ++, , . . .. - , , .

" ", volatile. BAD ADVICE , , "", . , , , , , "", . . , , ++ 11 , (, ++ 11)

+4

volatile , , volatile, (, , ). , CPU .

volatile int a = foo();
d=a+4;
e=a+4;
f=a+4;

a , . volatile, a+4 ( ) .

volatile int a = 4;
return a+5;

return 9;, a ( 1) ( 2);

+18

, k, , .

int k = 7;
int i = k;
int j = k;

:

int k = 7;
int i;
int j;
i = j = k;

volatile int k = 7;
int i = k;
int j = k;

.

+3

, , .

+1

, ?

, , ++ , . (.. , ).

volatile HW, . , , int, :

void foo( int & p );

HW, . , - - ++ .


volatile - cv-, , (, ).

++ [dcl.type.cv]/7 :

[: volatile - , , , . . 1.9 . , ++, C. - end note]

Volatile ? , volatile :

volatile C ++.

1) (I.e. , /.)
2) setjmp longjmp (ref: Volatile )

: :

, . :
     * setjmp, longjmp.
     * , , -, -      *

, , . , : *
* , , .

, volatile , , . (, ) ( .

0

The Volatile keyword is used to tell the compiler not to predict / assume / not believe / not to assume the value of a particular variable declared as mutable.

This variable can be changed by internal and external sources, so you can change it.

const volatile int k = 5; <==== This cannot be changed by your program, but can be changed by external sources, const does read only for the compiler or programmer

Source: - Volatile variable in C

0
source

All Articles