As mentioned in the title, I am little confused if the type-qualifiers
impact the storage location (stack
, bss
etc..) of the declarator.To describe more I am considering the following declarations.
int main()
{
const int value=5;
const char *str= "Constant String";
}
- In the above code, the default
storage-class-specifier
isauto
. - Hence it is assumed that these constants will be allocated in the
stack-frame
ofmain
when it is created. - Generally, the
pointers
to various memory locations in stack have the freedom to modify the values contained in it. - Hence from the above points it is understandable that, either the
type-qualifier
adds some logic to preserve theconstant
nature of the element stored (If so what is it?) or theconstants
are stored in aread-only-portion
of memory.Please elaborate on this.
More detailed example
#include <stdio.h>
int main(void)
{
int val=5;
int *ptr=&val;
const int *cptr=ptr;
*ptr=10; //Allowed
//*cptr=10; Not allowed
//Both ptr and cptr are pointing to same locations. But why the following error?
//"assignment of read-only location ‘*cptr’"
printf("ptr: %08X\n",ptr);
printf("cptr: %08X\n",cptr);
printf("Value: %d\n",*ptr);
}
In the above example, both cptr
and ptr
pointing to the same location. But cptr
is pointer to a const type qualified
integer. While modifying the value of cptr
, the compiler throws a error as "assignment of read-only location ‘*cptr’". But I am able to modify the same location with ptr
, as in the output below.Please explain
ptr: BFF912D8
cptr: BFF912D8
Value: 10