开发者

Effect of return type being static

开发者 https://www.devze.com 2023-02-12 02:32 出处:网络
What are the possible effect of returning a static type data. And when should we actually use it? static ssize_t

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 Uni开发者_高级运维x Network programming. 
      if (something)
         return (-1)
      if (something else)
          return (0)


      return (1)
}

why static here?

Thanks.


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.


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.


By using static , Access to static functions is restricted to the file where they are declared Another reason for making functions static is to reuse the same function name in other files.

//file1
static void fun1(void) 
{ 
  cout<<"file1";
} 


// file2
// now if we include file1 and use fun1 in file2 , it
// will show “undefined reference to `fun1’” error as 
// it fun1 is defined static

int main(void) 
{ 
  fun1();  
  getchar(); 
  return 0;   
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消