Search code examples
cpointerspass-by-referencepass-by-pointer

Is there something in C that is analogous to out/out keyword of C#?


void extract_left_subtree(node *right_child)
{
    while(right_child->right)
    {
        right_child = right_child->right;
    }  
    printf("rightmost inside the funtion is %d\n",right_child->data);
}

in this function the last line is printing the correct value.

 node *right_child=root;
 extract_left_subtree(right_child);
 printf("rightmost child is %d\n",right_child->data);

But here I'm getting some garbage value.

I know what the problem is, I know why it's happening, the only thing I don't know is how to rectify this? There are keywords like ref and out in C# which can be used to achieve the same but the issue is, how can we do the same in C language?

I don't want to return values from the method please


Solution

  • I don't want to return values from the method please

    If you don't want to return a value you can do:

    void extract_left_subtree(node **right_child)
    {
        while((*right_child)->right)
        {
            (*right_child) = (*right_child)->right;
        }  
        printf("rightmost inside the funtion is %d\n", (*right_child)->data);
    }
    

    and call it like:

    extract_left_subtree(&right_child);
    

    This passes the address of right_child to the function and then the function can directly update the value of right_child