[What] does const do in this case - const int *ptr;
Primarily what const
in that declaration does is require the compiler to warn you about certain misuses of the pointer. It does that by triggering these constraints in C 2018 6.5.16 1 and 6.5.16.1 1:
[6.5.16 1] An assignment operator shall have a modifiable lvalue as its left operand.
[6.5.16.1 1] … both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;…
and then the consequence of violating a constraint is that the compiler must produce a diagnostic message, per C 2018 5.1.1.3 1:
A conforming implementation shall produce at least one diagnostic message … if … a translation unit contains a violation of any syntax rule or constraint…
That is the primary effect: The compiler must help the programmer avoid mistakes by diagnosing these misuses of things qualified with const
.
I'm not sure how to test further.
You can test this by inserting either of these lines and attempting to compile:
*p_int = 0; // Will warn of a violation of the first constraint, attempting to assign to a non-modifiable lvalue.
int *q = p_int; // Will warn of a violation of the second constraint, discarding qualifiers in an assignment or initialization.
(The constraints apply directly to assignments, but other parts of the C standard, such as the rules for initialization, some conversions, and compound assignments, refer to the rules for assignments or simple assignments.)
When you define an object with const
(not just const
on a pointer to an object, but const
on the original definition of an object), then the compiler is allowed to put the object in memory protected from inadvertent modification and to make optimizations based on the assertion that the object will not be modified by the program. However, your declaration does not show such a use of const
.