Stav Alfi
Stav Alfi

Reputation: 13923

What is the proper way to add const?

I'm looking for a rule on how to add aditional protection using const.

For example:

int** p1 = ...;
int** const p2=p1; // Legal
int* const * const p3=p1; // Legal
int* const * const p4=p3; // Legal
const int* const * const p5=p3; // Error

int*** cube1= &p1;
int* const ** cube2=cube1; // Error
and so on...

Upvotes: 2

Views: 753

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

When it comes to rules of const-correctness in pointer conversions, C language supports implicit conversion from type T * to type const T * for non-array data type T. That's the only "const-protecting" implicit conversion that C language supports.

In other words, conversion from T * to const U * is supported if T and U are identical non-array types. If T is somehow different from U, the implicit conversion is invalid (even if the difference between T and U are just some extra const-qualifiers).

To put it in simple terms, you are allowed to add const only after the most inner *. You are not allowed to add const at any deeper level of indirection. This is why your lines with p5 and cube fail to compile.

int *p = 0;
const int *cp = p; // OK: `const` is added after the first `*`

int **pp = 0;
const int *const *cpp = pp; // Error: a "deep" `const` added 

Sometimes in your code you might need to circumvent these restrictions and add some extra const at deeper levels of indirection. In that case you have no choice but to use an explicit cast

int **pp = 0;
const int *const *cpp = (const int *const *) pp;  

P.S. C++ relaxed some of these limitations, creating a more logical system of const-correctness rules. Alas C never took any steps in that direction.

Upvotes: 2

Yousaf
Yousaf

Reputation: 29282

const generally applies to the value defined on the left side of it.

Example:

int const *ptr = &val;

in the above code snippet, const belongs to int and not the *ptr.

if you move * behind const, it will make ptr constant pointer

int *const ptr = &val;

now const belongs to pointer and not the int

Now see another example

const int *ptr = &val;

Only when there's a const on the left most side of a statement, it then applies to whatever is on the right side of it, in the above code snippet, it is int.

Upvotes: 2

Related Questions