3

i would like understand of uses of both?? what i understand by now is Node *root is a reference to root pointer to a node object on the other hand Node* root is pointer to node itself(allow you to pass by reference)

vivek_nitd
  • 61
  • 5
  • 5
    Assuming this is C then they are the same. – Paul R Dec 11 '16 at 10:20
  • There is no such thing as "ref" in C. – n. m. could be an AI Dec 11 '16 at 10:26
  • They both are the same and what they mean is that root is a pointer which is pointer towards a Node type. It means the root from now onwards will be able to store the address of a variable whose data type is also Node. When we say that a variable is pointer such as in your example, it means that the pointer you declared will be able to store memory address of other variables which are of the type with which that pointer itself was declared. Thats what pointing means (to store address of other variables or memory locations) . – Syed Ahmed Jamil Dec 11 '16 at 11:30

2 Answers2

11

The spacing is not significant in this definition, you could write all of the following interchangeably, they all define root as a pointer to a Node:

Node*root;

Node *root;

Node* root;

Node * root;

Node                        *root;  // I have seen that!

Node
*
root
;

Node(((*(root))));  // yes, this is allowed too!

\    
N\
od\
e*r\
oot ;          // ASCII art style: a corner case ;-) 

It is a matter of style, which you prefer to use. Just bear in mind these considerations:

  • Readability is very important to avoid silly and subtile bugs and make the code easier to maintain, whether it be by yourself or others.

  • Consistency is key to making the code readable: choose one style and use it everywhere.

  • Node * root looks like a multiplication, it tends to create confusion.

  • Tacking to * to the end of the type creates confusion if you declare multiple variables in the same statement:

    Node* root, tree;  // defines a pointer root and a structure tree.
    

    whereas

    Node *root, *tree; // defines 2 Node pointers root and tree.
    

    This is the reason many programmers prefer to tack the * to the identifier in the declarations.

    Using a typedef to hide the pointer nature as with typedef Node *Nodeptr;, or worse typedef Node *List; tends to be error-prone and create even more confusion in both the programmer's and the reader's minds.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
4

node *foo and node* foo are identical to the compiler.

!!Fun!! trivia you might not know. When you write what looks like a declaration of multiple pointers:

int* a, b; // two int*, right?

What the compiler sees is declarations for an int pointer and an int:

int *a;
int b;

To declare multiple pointers in one statement you must give each one a *:

int *a, *b;

or

int* a, * b;
Jack Deeth
  • 3,062
  • 3
  • 24
  • 39