In this function
/*following createList prints out only 1st element, why?*/
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else createList(root->next , a);
return root;
}
its parameter root is a local variable of the function that holds a copy of the value of the argument passed to the function. So changing the copy does not influence on the original argument.
Opposite to the above function in this function
/*following createList prints out fine */
node* createList(node* root , int a){
if(root == NULL) root = new node(a);
else root->next = createList(root->next , a);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return root;
}
there is an assignment of the original argument with the new value.
To make it more clear consider a very simple program
#include <iostream>
int f( int x )
{
x *= 10;
return x;
}
int main()
{
int x = 10;
std::cout << "Before call of f: " << x << '\n';
f( x );
std::cout << "After call of f: " << x << '\n';
x = f( x );
std::cout << "After call of f: " << x << '\n';
return 0;
}
Its output is
Before call of f: 10
After call of f: 10
After call of f: 100
After the first call of the function f the variable x in main was not changed because the function deals with a copy of its argument.
After the second call of the function the variable x was changed because it was reassigned by the new value.