Reputation: 61
Here is a ternary tree, I want to implement a search which finds if the id is in the tree. The function returns NULL in the current state(which is good), even though i did not add the line return NULL at the end of the function, why ?
struct T {
int id;
char * name;
struct T *left;
struct T *middle;
struct T *right;
};
T* findId(T* root, int id) {
if (root == NULL) {
return NULL;
}
if (root->id == id) {
return root;
}
T* sLeft = findId(root->left, id);
if (sLeft != NULL) {
return sLeft;
}
T* sMiddle = findId(root->middle, id);
if (sMiddle != NULL) {
return sMiddle;
}
T* sRight = findId(root->right, id);
if (sRight != NULL) {
return sRight;
}
}
Upvotes: 0
Views: 55
Reputation: 222714
C 2018 6.9.1 12 says:
Unless otherwise specified, if the
}
that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
It is “otherwise specified” as a special case for main
(C 2018 5.1.2.2.3 1); reaching the }
that terminates main
returns zero (unless the return type of main
is not compatible with int
). For your function, the behavior is not defined.
What may happen in such situations is that the code implementing the function does not put any particular value in the processor register that should be used to return a value. It merely leaves whatever value happened to be there from some prior work. When the caller tries to use the value of the function call, they get the leftover value in that register. However, this is of course not reliable. Your program may fail in other ways.
Compilers generally have a warning regarding this. You should enable most compiler warnings.
Upvotes: 5