Page 1 of 1

Regarding to return function

Posted: Fri May 16, 2003 5:50 am
by desmondlk
Dear all,

I have encountered a problem regarding to how to return the value back to the calling function.

This is the code that i used to test the problem.

Code: Select all

<?php
function test ($num, $cnt)
{
    if($cnt == $num){
        return $cnt;
    }
    else{
        $cnt+=1;
        test ($num, $cnt);
    }
}
$str = test (4, 3);
echo $str;

?>
The "$str" is empty. It does not pass the value back to the calling function.

However, if i comment this line "test ($num, $cnt);", it returns the value back to the calling function.
The "$str" is 4.

Code: Select all

<?php
function test ($num, $cnt)
{
    if($cnt == $num){
        return $cnt;
    }
    else{
        $cnt+=1;
        //test ($num, $cnt);
    }
}
$str = test (4, 4);
echo $str;

?>
Please help. Thanks in advance.

Re: Regarding to return function

Posted: Fri May 16, 2003 6:41 am
by Gleeb

Code: Select all

<?php
function test ($num, $cnt)
{
    if($cnt == $num){
        return $cnt;
    }
    else{
        $cnt+=1;
        test ($num, $cnt);
    }
}
$str = test (4, 3);
echo $str;

?>
becomes

Code: Select all

<?php
function test ($num, $cnt)
{
    if($cnt == $num){
        return $cnt;
    }
    else{
        $cnt+=1;
        return test ($num, $cnt);
    }
}
$str = test (4, 3);
echo $str;

?>

Posted: Fri May 16, 2003 6:48 am
by volka
funny, either this is some kind of joke or you have a real bad testing day ;)
let's take the first code-snippet and $str = test (4, 3);
  • $cnt != $num so the else-block is executed
  • $cnt+=1; // $cnt == 4
  • test($cnt, $num); // test(4,4)
  • now $cnt == $num
  • return $cnt;
  • but the "outer" function does not return this value
  • nothing's assigned to $str

$str = test (4, 4);
  • $cnt == $num
  • return $cnt; // return 4
  • $str = 4;
try

Code: Select all

<?php
function test($num, $cnt)
{
    if($cnt == $num){
        return $cnt;
    }
    else{
        $cnt+=1;
        return test($num, $cnt);
    }
}
$str = test(4, 3);
echo $str;

?>
edit:
:oops:
<-- way too slow

Posted: Fri May 16, 2003 6:53 am
by Gleeb
Don't worry, you know what they say... Great Minds Think Alike...

At least you explained it ;)

Posted: Fri May 16, 2003 7:00 am
by volka
today a can blame .NET studio :]
it seems to be clueless about the errors it encounters when combined with STLPort. It's more like Guess-Your-Fault ;)