0

Let's say I implement a tree in following way:

struct Node;
typedef struct Node Tree
struct Node {
int value;
Tree *left;
Tree *right;
};

Now i wanted to experiment with pointers to struct:

const Tree * a;

This works completely fine, I couldnt assign the value pointed by a to anything else, etc. However, I wanted to make things easier and changed typedef to following:

typedef struct Node * Tree

And now, even though it seems obvious that

const Tree a;

should behave the same way the previous declaration did, it doesnt, instead it behaves like a const pointer, meaning i cant write

a = ..stmh_else..

Why is that happening? Is it some nuance with typedef that I dont know?

Bluerain
  • 9
  • 4
  • 4
    "*However, I wanted to make things easier*" <- don't, just .... don't. Hiding pointers behind `typedef` is one of the worse ways to obfuscate code. –  May 04 '18 at 15:43
  • `const struct Node *` != `struct Node * const` – Patrick Roberts May 04 '18 at 15:45
  • 1
    Bottom line, no, it shouldn't perform the same way. The `typedef` ends up acting sort of like parentheses. When you say `const Tree a;`, the compiler doesn't "peek inside" of `Tree` to discover that it involves a pointer, it just applies the `const` to `a`. – Steve Summit May 04 '18 at 15:47

0 Answers0