1

My book says

typedef Card* Cardptr;

"defines the new type name Cardptr as a synonym for type Card*." I see that the * symbol modifies only Cardptr and that other synonyms if there were any more, are not modified by the * symbol. This is confusing to me. My book makes it seem like the actual structure type is Card*, which makes me think that other synonyms would have the type Card* as in

typedef Card* Cardptr, n;

where n would also have the type Card*. Wouldn't it be clearer if they moved * symbol like this?

typedef Card *Cardptr, n;

That way, you would know that the type is actually Card, that Cardptr is simply a pointer to it, and that n is not a pointer. What is the reason for this?

YSC
  • 38,212
  • 9
  • 96
  • 149
Marcus Kim
  • 283
  • 2
  • 12
  • 4
    Prefer [type aliases](http://en.cppreference.com/w/cpp/language/type_alias) to typedefs. Chances are you don't even need the typedef in C++. Structures are classes in C++, they are user-defined types so they can't be of some type. – Ron Sep 01 '17 at 00:51
  • 2
    If you think `typedef Card* Cardptr, n;` is ugly, wait until you try to apply it to a function pointer. You're better off placing them on separate lines for readability if nothing else. – user4581301 Sep 01 '17 at 00:52
  • 1
    Note on the last bit: "Why?" `typedef`s are interpretted much the same as a variable definition (In C at any rate and I have yet to see anything in C++ that differs) . `Card *Cardptr, n;` defines two variables: a pointer to `Card` `Cardptr` and a `Card` `n`. Slapping `typedef` in front defines two types: `Cardptr` as a pointer to `Card` and `n` as a `Card` – user4581301 Sep 01 '17 at 00:59
  • 1
    _"Wouldn't it be clearer if they moved * symbol ..."_ No it won't. To make it clearer, break it into two lines: `typedef Card* Cardptr;typedef Card n;` – Adrian Shum Sep 01 '17 at 02:24

1 Answers1

6

C++ generally does not care about whitespaces, so the two following statements are seen as identical by the compiler:

typedef Card* Cardptr;
typedef Card *Cardptr;

Similarly, the three declarations

int* a;
int *a;
int * a;

are indistinguishable.


Wouldn't it be clearer if they moved * [so] you would know that the type is actually Card, that Cardptr is simply a pointer to it, and that n is not a pointer. What is the reason for this?

The way a coder writes their declarations is only a matter of taste and style, and both are equally justifiable:

This would make me prefer int *a over int* a:

int* a,b; // declares and int* and an int; illogical, right?

This would make me prefer int* a over int *a:

int *a = 0; // a (an int*) is set to zero (a.k.a NULL), not *a; illogical, right?

Now, my advice: choose between those two forms and stick with it, consistently.

YSC
  • 38,212
  • 9
  • 96
  • 149