Error: control may reach end of non-void function in C++ - c++

I cannot figure out why this error is happening: error: "control may reach end of non-void function" even when "else" statement is present at the end.
Here is the code:
bnode* binsert(bnode *h,int k){
bnode *temp=new bnode;
if(h==NULL)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h=temp;
return h;
}
else if(h->L==NULL && k<h->num)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h->L=temp;
return h;
}
else if(h->R==NULL && k>h->num)
{
temp->num=k;
temp->L=NULL;
temp->R=NULL;
h->R=temp;
return h;
}
else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
}

You need to return the results of recursive calls, it's not done automatically.
You can also simplify your code a bit by adding a constructor:
bnode::bnode(int v)
: num(v),
L(nullptr),
R(nullptr)
{
}
and since you're already handling the case of a null parameter, you don't need special cases for null children:
bnode* binsert(bnode *h,int k)
{
if(h == nullptr)
{
h = new bnode(k);
}
else if(k < h->num)
{
h->L = binsert(h->L, k);
}
else if(k > h->num)
{
h->R = binsert(h->R, k);
}
return h;
}

because this last 2 conditions:
else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
may occur and no return is given...
you need to be sure the function returns a value no matter what the condition evaluates....

else if(h->L!=NULL && k<h->num)
{
h->L=binsert(h->L,k);
}
else
{
h->R=binsert(h->R,k);
}
In the else if and else cases for your code, if you reach here, you do not return a value, and the behavior is undefined if you try to use this value.
You probably want to add a return h; in the two branches.

Related

c++ how to get depth of a binary tree recursively

I wrote a code that suposed to return the depth of a binary tree from the root to the node who called the function. using recursive way but I faced a problem about how to count the number of times that the function gets called so I whould know how much convexity I passed. Someone know how can I do that?
int BSNode::getDepth(const BSNode& root) const
{
if (this != nullptr)
{
if (root.getData() > this->_data)
{
this->getDepth(*root.getRight());
}
else if (root.getData() < this->_data)
{
this->getDepth(*root.getLeft());
}
else if (root.getData() == this->_data)
{
// return the number that the function counted
}
}
else
{
return 0;
}
}
You should at least return something in every case. And when you arrive at the intended node (having the data you are looking for), then return 0. In all other cases, return what you get from recursion plus 1. If the value is not found then indeed -1 should be returned. And if this -1 is coming back from recursion, it should be returned like that also to the caller (without adding 1).
Here is the code adapted:
int BSNode::getDepth(const BSNode& root) const
{
int temp;
if (this != nullptr)
{
if (root.getData() > this->_data)
{
temp = this->getDepth(*root.getRight());
return temp == -1 ? -1 : temp + 1;
}
else if (root.getData() < this->_data)
{
temp = this->getDepth(*root.getLeft());
return temp == -1 ? -1 : temp + 1;
}
else if (root.getData() == this->_data)
{
return 0;
}
}
else
{
return -1;
}
}

Can somebody tell me how this code working with no curly braces between two if?

If I am enclosing the code after first if upto second return in curly braces it is not giving me desired output.
static int comparator(Player a, Player b) {
if(a.score == b.score)
if(a.name == b.name)
return 0;
else
return (a.name > b.name)? -1:1;
return (a.score < b.score)? -1:1;
}
Your code has if() and else statements. Each will execute one line of code that comes after them. This means that it will only execute a single statement and end after the first ; that it finds.
for() loops, while() loops, if-else blocks can be used without curly braces if the statement you want to execute consists of only one line of code following them.
Your code works as -
static int comparator(Player a, Player b) {
// if statement without braces- means just one statement executes
if(a.score == b.score)
// Remember if-else will be considered as a single code block so both will run
if(a.name == b.name)
return 0;
else
return (a.name > b.name)? -1:1;
// This statement will run only when the above if condition is not satisfied
return (a.score < b.score)? -1:1;
}
This can be considered to be same as -
static int comparator(Player a, Player b) {
if(a.score == b.score) {
if(a.name == b.name) {
return 0;
} else {
return (a.name > b.name) ? -1 : 1;
}
}
return (a.score < b.score) ? -1 : 1;
}
NOTE : It is generally better if you use the braces as it will be good for readability as well as maintainability of the code. There can actually be two way of parsing it - Dangling else(though most compiler will associate the else with closest if).
In this coding style, there's no way to differentiate between below two code -
if(condition1)
if(condition2)
foo1();
else
foo2();
and,
if(condition1)
if(condition2)
foo1();
else
foo2();
Since, in C/C++, it doesn't consider the indentation in code, so it might create ambiguity while reading the code. So its always better to use curly braces instead of doing it like above. Drop them only when you have a single line and it won't create any confusion reading the code later on...
Hope this helps !
Without curly braces, only the next statement is executed. With proper indentation it becomes easier to see what's going on:
static int comparator(Player a, Player b) {
if(a.score == b.score)
if(a.name == b.name)
return 0;
else
return (a.name > b.name) ? -1 : 1;
return (a.score < b.score) ? -1 : 1;
}
This is actually the same as:
static int comparator(Player a, Player b) {
if(a.score == b.score) {
if(a.name == b.name) {
return 0;
} else {
return (a.name > b.name) ? -1 : 1;
}
}
return (a.score < b.score) ? -1 : 1;
}
You have maybe used the braceless else variant without noticing it when writing something like:
if(condition) {
//
} else if(another_condition) {
//
} else {
//
}
Which is actually the same as
if(condition) {
//
} else {
if(another_condition) {
//
} else {
//
}
}
Without curly braces, the if guard only applies to the immediate next statement.
It's just how the language works. :/

Sorting linked list in C++ fails at runtime

void head_insert(DomesticPtr& head, string firstNameD, string lastNameD, string province, float cgpaD, int researchScoreD, int idD)
{
DomesticPtr temp_ptr;
DomesticPtr temp2;
temp_ptr= new DomesticStudent(head, firstNameD, lastNameD, province,cgpaD,researchScoreD,idD);
temp2 = head->getLink();
temp2==temp_ptr;
head=temp_ptr;
if (head->getLink() == NULL)
return;
else
{
bubblesort(head);
}
}
void bubblesort(DomesticStudent* head)
{
int rsd;
int cgpad;
int p;
DomesticPtr tempc, tempd, tempe;
tempd=head;
tempe= head->getLink();
{
while(tempd != NULL)
{
rsd=compareResearchScore(tempd, tempe);
if (rsd==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if
else if (rsd==0)
{
cgpad= compareCGPA(tempe,tempd);
if (cgpad==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (cgpad[k]>cgpad[k+1])
else if(cgpad==0)
{
p=compareProvince(tempd,tempe);
if(p==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (p[k]>p[k+1])
}//
}// else if cgpad[k]
}// else if rsd[k]
// }
// }
tempd = tempe;
}
int compareResearchScore(DomesticPtr RSA, DomesticPtr RSB)
{
if (RSB == NULL || RSA==NULL )
{
return 0;
}
if (RSA->researchScoreD==RSB->researchScoreD) //compares if is the same for domesetic students returns value for bubble sort
{
return 0;
}
if (RSA->researchScoreD > RSB->researchScoreD)
{
return 1;
}
if (RSA->researchScoreD< RSB->researchScoreD)
{
return -1;
}
}
I'm trying to to have my linked list sorted every time a new node is inserted. It compiles but every time I try to run the program it is stuck on the point that I am trying to print my list. I have a destructor but no copy constructor or assignment operator.
The head_insert calls the sort function and the sort function calls the compare function to receive an integer output so that it can make a swap. I want to compare research, the cgpa, and then province. Any input would be much appreciated, this is for a project so I wouldn't like any blocks of code but if you could point me in the right direction or multiple directions.

Refactor several nested if with same else

This is not about an existing piece of code but I'm looking for some pattern that may exist in the case that some nested if perform the same thing in their else statement.
if(condition1(a)) {
doSomethingWith1(a);
if(condition2(a)) {
doSomethingWith2(a);
} else {
elseFn();
}
} else {
elseFn();
}
The doSomethingWith... functions are changing the value of a, making it complex to have all the condition in one if.
So I'm just wondering if there is a clearer way to write it (in C, if possible).
Thanks guys
in your case, looks like the first if, if(condition1(a)), is absolutely necessary to test for the value of a before calling doSomethingWith1(a); to avoid an exception. so, no, there is no other way to do it.
if(condition1(a)) {
doSomethingWith1(a);
if(condition2(a)) {
doSomethingWith2(a);
} else {
elseFn();
}
} else {
elseFn();
}
You could just keep a count of the "doSomethings" and invoke the elseFn unless all were executed.
int count = 0;
if (condition1(a)) {
doSomethingWith1(a);
count++;
if (condition2(a)) {
doSomethingWith2(a);
count++;
if (condition2(a)) {
doSomethingWith2(a);
count++;
}
}
}
if (count < 3) {
elseFn();
}
I find it more readable, though less efficient, to double-check the first condition. This refactoring eliminates nesting, without multiple functions. It also more clearly shows three distinct paths of execution by grouping each logical path into a single code block.
if (condition1(a) && condition2(a)) {
doSomethingWith1(a);
doSomethingWith2(a);
}
else if (condition1(a)) {
doSomethingWith1(a);
elseFn();
}
else {
elseFn();
}
I don't know in C but in Java you could write this as the following:
void function(int a) {
boolean b1 = condition1(a);
if (b1) {
doSomethingWith1(a);
boolean b2 = condition2(a);
if (b2) {
doSomethingWith2(a);
}
}
if (b1 || b2) {
return;
}
elseFn();
}

Error: not all control paths return a value

I am writing two functions in a program to check if a string has an assigned numeric code to its structure array or if the given numeric code has an assigned string in the same structure array. Basically, if I only know one of the two, I can get the other. I wrote the following:
int PrimaryIndex::check_title_pos(std::string title) {
bool findPos = true;
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
} else {
return -1;
}
}
std::string PrimaryIndex::check_title_at_pos(int pos) {
bool findTitle = true;
if (findTitle) {
for (int p = 1; p <= 25; p++) {
if (my_list[p].tag == pos) {
return my_list[p].title;
}
}
} else {
return "No title retrievable from " + pos;
}
}
However, it says not all control paths have a return value. I thought the else {} statement would handle that but it's not. Likewise, I added default "return -1;" and "return "";" to the appropriate functions handling int and string, respectively. That just caused it to error out.
Any idea on how I can keep this code, as I'd like to think it works but cant test it, while giving my compiler happiness? I realize through other searches that it sees conditions that could otherwise end in no returning values but theoretically, if I am right, it should work fine. :|
Thanks
In the below snippet, if s iterates to 26 without the inner if ever evaluating to true then a return statement is never reached.
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
}