简体   繁体   中英

How do typedef-ed pointers work

typedef int* ptr_t;
int target;
const ptr_t a = ⌖
*a = 6;            //OK
a = &target;       //<- error: assignment of read-only variable ‘a’

Clearly, the pointer is constant, and not the value pointed. This is in contrast if a #define was used.

What are the rules for applying modifiers to pointers, declared in a typedef?

For a practical example, consider the code void (**foo)(void);

  • How would one go about typedef-ing a type, that qualifies the top-level pointer as const(eg pointing to a hardware location), the next pointer as volatile (eg modifiable by independent hardware) pointer to a function?

  • typedef void (**foo)(void) If this is the fixed declaration that we have to work with, ow d owe do the above operation in the source code?

The rule is:

  • typedef is not pure textual replacement like a macro.
  • The declaration is not parsed to see that there is a pointer involved in typedef
  • The cv qualifier applies to the synonym you created with typedef ie: int * .

So,

typedef int* ptr_t;
const ptr_t a = &target;

is not same as:

const int* a;

but it is same as:

int *const a;

Put in words, First declares a const constant pointer to int, not pointer to constant int as in second.

As you just noticed from your example,
It is a bad practice to typedef pointers because it reduces the code readability and intuitiveness. It ie very easy to create bugs while using typedef for pointers. It is best to avoid it.

Section 6.7.5.1 of the C standard describes the difference. It gives as an example:

const int *ptr_to_constant;
int *const constant_ptr;

And says:

The contents of any object pointed to by ptr_to_constant shall not be modified through that pointer, but ptr_to_constant itself may be changed to point to another object. Similarly, the contents of the int pointed to by constant_ptr may be modified, but constant_ptr itself shall always point to the same location.

Finally, point 4 in that section describes the use of typedefs.

The declaration of the constant pointer constant_ptr may be clarified by including a definition for the type ''pointer to int''.

  typedef int *int_ptr;
  const int_ptr constant_ptr;

declares constant_ptr as an object that has type ''const-qualified pointer to int''.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM