Οκ. But I am not sure that I have understood the usefulness of volatile keyword. I was confused because I had read the following about the volatile from a book:
[I] To see why volatile is needed , suppose that a pointer p points to a memory location that contains the most recent character typed at the user's keyboard. This location is volatile: its value changes each time the user enters a character. We might use the following loop to obtain characters from the keyboard and store them in a buffer array :
Code:
while( buffer not full) {
wait for input;
buffer[i] = *p;
if ( buffer[i++] == '\n' )
break;
}
A sophisticated compiler might notice that this loop changes neither *p nor p. So it could optimize the program by altering it so that *p is fetched just once :
Code:
store *p in a register
while(buffer not full) {
wait for input;
buffer = value stored in register;
if (buffer[i++] = '\n')
break;
}
The optimized program will fill the buffer with many copies of the same character not exactly what we have in mind.Declaring tha p points to volatile data avoids this problem by telling the compiler that *p must be fetched from memory every time it is needed.
I can't understand the last lines. What is the problem we avoid? and how your explanation about volatile can solve it. If you want to fetch only the different characters and not the same for example enter twice the character 'a' how you can achieve this according to volatile's theory you said that load even the redudant assignments.
"fetching" I think is when you get something from the memory I am right?