Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect of return type being static

Tags:

c

What are the possible effect of returning a static type data. And when should we actually use it?

static ssize_t
my_read(int fd, char *ptr)
{
    //code from Stevens Unix Network programming. 
      if (something)
         return (-1)
      if (something else)
          return (0)


      return (1)
}

why static here?

Thanks.

like image 786
freedesk Avatar asked Feb 17 '11 05:02

freedesk


People also ask

Can static function have a return type?

it is a static method (static), it does not return any result (return type is void), and. it has a parameter of type array of strings (see Unit 7).

What is a static return type?

static return type follows Liskov Substitution Principle. A child class method can return a narrower class object than the parent methods return type. Because static always refer to the class name of the called object (i.e. same as get_class($object) ), static is a subset of self , which in turn is subset of parent .

Can static variables be returned?

It is the variable that is static, not its value. In fact, however, it would also be fine to return a pointer to the variable ( &person_p ), which is as close as you can come to returning the variable itself.

Can static method have return type in Java?

In Java, a static method may use the keyword void as its return type, to indicate that it has no return value.


2 Answers

The function is static, not the return type. This means that its name is only visible from within the current compilation unit, which is used as an encapsulation mechanism.

The function can still be called from elsewhere through a function pointer, however.

See also this discussion on the general static keyword for more context.

like image 173
Marcelo Cantos Avatar answered Sep 27 '22 18:09

Marcelo Cantos


We use static data type when returning a pointer to a variable created in called function.for e.g

float * calculate_area(float r) 
{
    float *p;
    static float area;   
    p=&area;   
    area=3.14*r*r;
    return p;
}

If you would make area as automatic variable i.e without any type qualifier it would be destroyed when control returns from called function.When declared as static you could correctly retrieved the value of area from main also.Thus it in order for it to persists its value we make it as static.

like image 38
Algorithmist Avatar answered Sep 27 '22 20:09

Algorithmist