Home > OS >  Interperting const points with typedefs
Interperting const points with typedefs

Time:11-19

I am trying to understand this const and pointers.

typedef cu::Op const * operation_t; 
typedef operation_t const * const_operation_ptr_t;

Is operation_t a pointer to a const cu::Op object?

And so on the second line, if you substitute operation_t you get cu::Op const * const *.

Does this mean that const_operation_ptr_t is a constant pointer (its address cannot change) which is pointing to a constant object who's value cannot be changed?

CodePudding user response:

Does this mean that const_operation_ptr_t is a constant pointer

No, const_operation_ptr_t is a non-const pointer to const pointer to const cu::Op. It could be changed, i.e. make it pointing to another object, but the object pointed by it can't be modified.

If you want const_operation_ptr_t to be const, you could

typedef operation_t const * const const_operation_ptr_t;
//                          ^^^^^

BTW: operation_t is a non-const pointer to const cu::Op.

CodePudding user response:

The typedef name operation_t denotes a non-constant pointer to a constant object of the type cu::Op.

typedef cu::Op const * operation_t; 

The typedef name const_operation_ptr_t denotes a non-constant pointer to a constant pointer of the type cu::Op const *.

typedef operation_t const * const_operation_ptr_t;

To make the both introduced pointer types as types of constant pointers you need to write

typedef cu::Op const * const operation_t; 

and

typedef operation_t const * const const_operation_ptr_t;

A more simple example. These two declarations

const int *p;

and

int const *p;

are equivalent and declare a non-constant pointer to an object of the type const int.

This declaration

int * const p = &x;

declares a constant pointer to a non-constant object of the type int.

These declarations

const int * const p = &x;

and

int const * const p = &x;

are equivalent and declare a constant pointer to a constant object of the type const int.

  • Related