Search code examples
c++pointerslinked-list

Difference between *pointervar and (*pointervar)


On this page I've found the following code:

//insert a new node in front of the list
void push(struct Node** head, int node_data)
{
   /* 1. create and allocate node */
   struct Node* newNode = new Node;
 
   /* 2. assign data to node */
   newNode->data = node_data;
 
   /* 3. set next of new node as head */
   newNode->next = (*head);
 
   /* 4. move the head to point to the new node */
   (*head) = newNode;
}

Now I'd like to know why in the third line *head is in brackets? What is the difference between *head and (*head) ?


Solution

  • What is the difference between *head and (*head) ?

    The brackets around *head are not needed. You can remove the brackets. It would have the effect as with brackets.

    Usually, we explicitly put brackets around an expression, to circumvent/override operator precedence rules.

    But in your example, there is no difference with or without brackets .


    An example where the parenthesis are needed is shown below:

    struct C
    {
        void f(int);
    };
    
    int main() {
        auto ptr = &C::f;
        C c;
        (c.*ptr)(5); //PARENTHESIS NEEDED HERE ; this compiles
       // c.*ptr(5);   //this won't compile! because of operator precedence rules   
    }