c++ - Why do I get two return values here? -


int main(){  int recurse(int); int a=recurse(0); printf(" return %d",a); } 

first one:

 int recurse(int c){ //printf("%d", c); if(c<10){    recurse(c+1); }else{ return(c); }  } 

second one:

int recurse(int c){ //printf("%d", c); if(c<10){    recurse(c+1); } return(c); }  

in first one..i return value of 10 while in second 1 return value of 0. why 2 different values , why 0??

in fact function

int recurse(int c){ //printf("%d", c); if(c<10){    recurse(c+1); }else{ return(c); }  } 

has undefined behaviour because returns nothing in case when c < 10

this function

int recurse(int c){ //printf("%d", c); if(c<10){    recurse(c+1); } return(c); }  

always returns value of argument c independently of value itself. function has unconditional return statement , returns argument. called argument equal 0 returned it.:)

a correct function following way

int recurse( int c ) {     return c < 10 ? recurse( c + 1 ) : c; } 

of course written simpler without recursion :)

int recurse( int c ) {     return c < 10 ? 10 : c; } 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -