Upgrayded Upgrayded - 4 months ago 31
C++ Question

Function not returning default value C++

This code will return the values of 1 or 0 when those returns are called, but if it falls to the default return value of 2, it doesn't return it. I'm sure it's something small I'm missing, but I can't figure it out.

int comp(string a, string b){
char x;
char y;
int i = 1;
int len;
len = a.length();
if(b.length() < (unsigned)len){
len = b.length();
x = a.at(i);
y = b.at(i);
if(getNum(x) < getNum(y)){
return 1;
else if (getNum(x) > getNum(y)){
return 0;
return 2;




Delete below code on top of the while loop


You are actually getting an exception there. Because on the last run, you are having indexoutofbound exception.

If your string is "hello" the length is 5 which mean your index is 0,1,2,3,4.

h e l l o
0 1 2 3 4

With your len++ it raised the length to 6. And on the last round of while(5< 6) you are tring to access index of 5 which does not exist

Hope it helps