Hi All,
I have doubts in storage classes in C. Where does variables declared with auto , static , extern , register , volatile and const stored?
What is the use of BSS Segment?
Hi All,
I have doubts in storage classes in C. Where does variables declared with auto , static , extern , register , volatile and const stored?
What is the use of BSS Segment?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Using register, volatile and const are just requests to the compiler; they don't necessarily change the where a variable is stored.
register requests that the compiler store the object in a machine register, but it doesn't have to fulfill this request.
const requests that the compiler will disallow you from modifying a variable's contents, but it doesn't guarantee to do this. For example, you might have a pointer to the same location and then modify it anyway. Or, the compiler might just issue a warning if you try to change a const variable.
volatile means that the compiler can't assume exclusive control over the memory area you've designated. Example:
What will the result be? If it is not volatile, the compiler may decide to ignore the fact that you assigned 1234 to location 0xffff and just replace the *x in printf with a literal 1234. volatile asks the compiler not to do such a thing.Code:volatile int *x = (int*)0xffff; *x = 1234; sleep(1); printf("%d\n", *x);
Hi c99tutorial,
Volatile refers that the compiler cant have exclusive control over the memory space designated. What does it mean exclusive control here? I am just confused with that. If so the control over the memory space is not available, then how can we have access over it?
The program above is mentioning a seg fault.
It is only an example, not a realistic one. The area 0xffff is probably outside your program's legal range, hence the segfault. Replace 0xffff with an address that is acccessible to your program.
Volatile simply means that the area could change at any time, for example maybe there is a hardware device memory mapped to that address. Or maybe you have another process running that is going to write to that location as a way of inter-process communication. Without the volatile keyword, the compiler assumes that your program is the only one that uses a particular location x and can use this fact for optimizations. However, if you know that this is not the case, you can use volatile to ensure that the compiler doesn't assume that.