static variable function

static variable

#include "iostream.h"

int p(int x)
{
static int y=1;
y=y+1;
return (x+y);}
int main()
{
cout<<p(1)<<endl;
cout<<p(2)<<endl;}


The answer is 3 and 5, why not 3 and 4?


Static variables in c language are allocated memory for them when the program is loaded, until the end of the program, unlike ordinary variables, which are allocated once by function execution. So when p(1) is executed for the first time, y has already been incremented by 1. When p(2) is executed next time, y will not be restored to 1 or 2; you can just treat it as the function of the global variable. There is a difference


static function

Functions decorated with static are limited to this source code file and cannot be called by code files other than this source code file. For ordinary functions, the default is extern, that is, the function can be called by other code files. The function is defined as a static function by adding the keyword static before 
  the return type of the function. The definition and declaration of ordinary functions are extern by default, but static functions are only visible in the file where they are declared, and cannot be used by other files. Therefore, defining a static function has the following advantages:
  <1> Functions with the same name can be defined in other files without conflict.
  <2> Static functions cannot be used by other files.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325608799&siteId=291194637