Why should we always return values ​​from a function?

I am not a big programmer, but many times I listen from programmers that we should always return values ​​from a function. I want to know the reason.

+5
source share
9 answers

The function should not return anything ... If you look at the C (++) function, many of them are not (well, not explicitly):

void nonReturningFunction(const int *someParam);
int main()
{
    int i = 12;
    nonReturningFunction(&i);
    return 0;
}
void nonReturningFunction(const int *someParam)
{
    printf("I print the value of a parameter: %d",someParam);
}

The latter returns nothing, well, it returns the void. The main function returns something: 0it is usually a signal to the system so that it knows that the program is finished and it ended well.

PHP . , , -. , .

, :

<?php
    class Foo
    {
        private $foo,$bar;
        public function __construct()
        {
            $this->foo = 'bar';
        }
        public function getFoo()
        {
            return $this->foo;//<-- getter for private variable
        }
        public function getBar()
        {
            return $this->foo;//<-- getter for private variable
        }
        public function setBar($val = null)
        {
            $this->bar = $val;
            return $this;//<-- return instance for fluent interfacing
        }
        public function setFoo($val = null)
        {
            $this->foo = $val;
            return $this;
        }
    }
    $f = new Foo();
    $f->setFoo('foo')->setBar('bar');//<-- fluent interface
    echo $f->getFoo();
?>

setter , :

$f->setFoo('foo');
$f->setBar('Bar');

, . , :

function manipulateArray(array &$arr)//<-- pass by reference
{
    sort($arr);
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is sorted

:

function manipulateArray(array $arr)//<-- pass by copy
{
    sort($arr);
    return $arr;
}
$arr = range('Z','A');
manipulateArray($arr);
var_dump($arr);//array is not sorted!
$arr = manipulateArray($arr);//<-- requires reassign

, . , , . , , .

+6

. , Fortran, - , int, float, bool .. C "void" C, return, . Java, , , . , "void" :

//This works
public void boo() {
   return;
}


//This gets you an error
public int boo() {
   return;
}

//This gets you an error too, because you must specify a type for any function in Java
public boo() {
   return;
}

, , -, , . , / . int, , "1" "-1". Unix .

, PHP, , PHP - "void" , .

,

+7

. , .

, .

+6

...

: , . , .

, , .

+5

, , ( ) .

, , , ( ) , .

. , , . , (.. ).

, , @lix, - . , , - . , , .

, - . , , , - , .

+3

: . echo ing vs return . , , true false , , - , . .

+2

. ( - ). -. , - , , ( C). . , , , , . ( , ), .

, , , , , , , .

+1

. , - , ; , ; ( C++), ( , PHP). , , , , ? , , (, ). IDE , , . , .

0

, . . , , . , PHP, , . php:

PHP

- , , - , " "

0

All Articles