C++ typedef interpretation of const pointers
Asked Answered
E

2

28

Firstly, sample codes:

Case 1:


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

Textually replacing CHARS becomes:


typedef char* const CPTR;   // still a constant pointer to chars

Case 2:


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

Textually replacing CHARS becomes:


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

In case 2, after textually replacing CHARS, the meaning of the typedef changed. Why is this so? How does C++ interpret this definition?

Esma answered 12/2, 2010 at 17:27 Comment(2)
In general, it is a bad idea to typedef pointers (hiding the star), precisely because const cannot be inserted between the pointed-to-type and the star anymore.Spadework
Sort-of duplicate of #1808971Handbag
S
42

There's no point in analyzing typedef behavior on the basis of textual replacement. Typedef-names are not macros, they are not replaced textually.

As you noted yourself

typedef CHARS const CPTR;

is the same thing as

typedef const CHARS CPTR;

This is so for the very same reason why

typedef const int CI;

has the same meaning as

typedef int const CI;

Typedef-name don't define new types (only aliases to existing ones), but they are "atomic" in a sense that any qualifiers (like const) apply at the very top level, i.e. they apply to the entire type hidden behind the typedef-name. Once you defined a typedef-name, you can't "inject" a qualifier into it so that it would modify any deeper levels of the type.

Saldivar answered 12/2, 2010 at 17:40 Comment(0)
S
14

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.

Skater answered 12/2, 2010 at 17:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.