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
Post a Comment