C++ typedef interpretation of const pointers

前端 未结 2 769
小蘑菇
小蘑菇 2020-11-29 06:50

Firstly, sample codes:

Case 1:


typedef char* CHARS;
typedef CHARS const CPTR;   // constant pointer to chars

Textually replacing C

2条回答
  •  感情败类
    2020-11-29 07:25

    Typedef is not a simple textual substitution.

    typedef const CHARS CPTR;
    

    Means "the CPTR type will be a const CHARS thing." But CHARS is a pointer-to-char type, so this says "the CPTR type will be a const pointer-to-char type." This does not match what you see when you do a simple substituion.

    In other words,

    typedef char * CHARS;
    

    is not the same as

    #define CHARS char *
    

    The typedef syntax is like a variable declaration, except that instead of declaring the target name to be a variable, it declares it as a new type name which can be used to declare variables of the type that the variable would be without the typedef.

    Here's a simple process for figuring out what a typedef is declaring:

    1. Remove the typedef keyword. Now you will have a variable declaration.

      const CHARS CPTR;
      
    2. Figure out what type that variable is (some compilers have a typeof()operator which does exactly this and is very useful). Call that type T. In this case, a constant pointer to (non-constant) char.

    3. Replace the typedef. You are now declaring a new type (CPTR) which is exactly the same type as T, a constant pointer to (non-constant) char.

提交回复
热议问题