Home > Software engineering >  What value is returned from a function implicitly if no value is returned explicitly from a function
What value is returned from a function implicitly if no value is returned explicitly from a function

Time:01-16

This is a code to find least common ancestor of n1 and n2 in a binary tree

Node * lca (Node* root, int n1, int n2)
{
  if (root == NULL)
    return NULL;

  if (root->data == n1 or root->data == n2)
    return root;
  
  Node *l = lca(root->left, n1, n2);
  Node *r = lca(root->right, n1, n2);
  
  if (l and r)
    return root;

  //return (l != NULL) ? l : r;
}

I took a random binary tree as shown below

    1
   / \
  2   3
 / \ / \
4  5 6  7

When the function call goes to node with value 5 there is no pointer to node that is returned to the caller function. So what value will be assigned to r in that case?

I tried assuming that by default it returns a NULL pointer, so if (r == NULL), I tried to print a number, but I got no value in output.

I tried using the keyword undefined like in javascript but to no avail. It is showing error. what does it mean to not return any value in a function that has a return type?

CodePudding user response:

If you have function that is declared with a return type other than void and in a call to the function the closing } is reached without an intervening return statement, then your program has undefined behavior.

Undefined behavior means that you lose any guarantees on the behavior of the program. Any outcome is possible. It could behave as if you had written return NULL;, it could behave as if returning a random value, it could behave as if the call never happened and it doesn't have to be consistent in any way. This is true not only for the offending function call, but the whole program (with given input), also the parts leading up to the function call. Such a program is simply invalid and broken. It is pointless to think about its behavior.

So don't do that. Compilers will warn you about the possibility of running off the end of a non-void function if you enable warnings. If yours didn't, then check how to enable a higher warning level for your compiler.

I tried using the keyword undefined like in javascript but to no avail.

There is no equivalent to that in C .

Also, if you are coming from javascript, then you need to be especially careful, since javascript (as far as I know) has no equivalent of C's and C 's undefined behavior. Understanding the significance of this concept and remembering which situations cause it, is something that new users of the language coming from other languages often seem to have problems with. In C and C you are not guaranteed to be notified with a warning or error at either compile- or runtime if your program is broken. It will simply have arbitrary behavior that may or may not seem to work as expected under undefined behavior.

  • Related