When I change the value that I pass to my array I receive strange error which doesn't stop the program but it always appears so I'm curious why. I give you my code below: My error is something like: In function 'int numOfDifferentElements(BSTree*, int)': control reaches end of non-void function [-Wreturn-type] ( main.cpp:97:1 ) and there is an arrow pointing to: }
#include <iostream>
using namespace std;
struct BSTree
{
int val;
BSTree* up;
BSTree* right;
BSTree* left;
};
void AddBstNode(BSTree* &root, int valToAdd)
{
{
BSTree* pom;
BSTree* nodeToAdd = new BSTree;
nodeToAdd->val = valToAdd;
nodeToAdd->left = NULL;
nodeToAdd->right = NULL;
nodeToAdd->up = NULL;
if (root == NULL)
{
root = nodeToAdd;
}
else
{
pom = root;
while (1)
{
if (nodeToAdd->val < pom->val)
if (pom->left == NULL)
{
pom->left = nodeToAdd;
break;
}
else
pom = pom->left;
else if(nodeToAdd->val > pom->val)
{
if (pom->right == NULL)
{
pom->right = nodeToAdd;
break;
}
else
pom = pom->right;
}
else // gdy wartosc jest rowna to jej nie dodajemy do drzewka aby potem mozna bylo zliczyc el drzewa
// a kazdy z nich bedzie inny
{
break;
}
}
nodeToAdd->up = pom;
}
}
}
int numOfDifferentElements(BSTree* root, int counter)
{
if (root)
{
counter ;
numOfDifferentElements(root->left, counter);
numOfDifferentElements(root->right, counter);
}
else
{
return counter;
}
}
void judgeArray(int array[], int x)
{
BSTree* pom = NULL;
int lengthOfArray = *(&array 1 ) - array; // rozmiar naszej tablicy
for(int i = 0; i < lengthOfArray; i )
{
AddBstNode(pom, array[i]); // tworzymy drzewo z elementow naszej tablicy
}
int counter = 0;
int judge = numOfDifferentElements(pom, counter); // zliczamy liczbe el drzewa, bez zadnych zalozen, bo
//wszystkie jego elementy sa rozne co zostalo zapewnione w funkcji AddBstNode ( kom. w linii 76 i 77)
if(judge == x)
{
cout<<"Array is good"<<endl;
}
else if(judge < x)
{
cout<<"Array is wrong"<<endl;
}
else if(judge > x)
{
cout<<"Array is mediocre"<<endl;
} // powyzej nasze zalozenia, jesli liczba roznych el jest mniejsza/wieksza/rowna od naszego zalozonego x ( liczby
//roznych elementow) to tak oceniamy nasza tablice
}
int main() {
int N[16] = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8}; // przykladowa tablica
int x = 12; // przykladowa wart x
judgeArray(N, x); // wywolanie naszej funkcji z przykladowa wartoscia
return 0;
}
CodePudding user response:
The problem is that in your numOfDifferentElements
function, if the if
condition is satisified then there is no return statement. The problem is because the return type of the function is non-void and so you must return something. You can solve this by adding a return
statement inside the if
block or outside(after) the else
block as shown below:
int numOfDifferentElements(BSTree* root, int counter)
{
if (root)
{
counter ;
numOfDifferentElements(root->left, counter);
numOfDifferentElements(root->right, counter);
//can also add a return statement here
}
else
{
return counter;
}
//or add return -1; or some other value indicating ERROR CODE
}