Is the value of *b undefined when printf() is called?
void foo(int *a) {
const int *b = a;
int *c = a;
*c = 2;
printf("%d\n", *b); // what must be *b? 1, 2 or undefined?
}
int d = 1;
foo(&d);
The pointer argument '%argument%' for function '%function%' can be marked as a pointer to const (con. 3). A function with a T* argument has the potential to modify the value of the object. If that is not the intent of the function, it is better to make the pointer a const T* instead.
Pointers with Const Memory Address Pointers with a constant memory address are declared by including the const after the *. Because the address is const, the pointer must be assigned a value immediately.
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
A const pointer is a pointer whose address can not be changed after initialization.
It will print 2. const int *b
literally means:
Pointer to an integer whose value cannot be altered through its dereferentiation.
This does not mean that the value the pointer points to may not change. In fact it's perfectly valid to change. A likely scenario to use this, are structures that keep a read only reference to some large structure. The reference may change, but the functions working with that structure may not change what's behind the pointer.
Imagine a driver or similar that hands out a read only memory mapping of whatever data the device delivered: The address of the mapping is not constant, but since this is a read only mapping the user program may not write to it. OTOH when the device updates the data the contents of the buffer will change, but not necessarily the mapping address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With