static

静态变量有一个特点,即使超出其作用域后也能保持其值!(多想想C语言的5个分区)

因此,静态变量在其前一个作用域中保留其前一个值,并且不会在新作用域中再次初始化。

C语言划分为5个分区

  • 全局/静态存储区
  • 堆 stack: 先入先出(new关键字创建->delete删除)
  • 栈 heap:通常动态内层分配的地方,后入先出, 函数的创建是在栈中
  • 自由存储区:free
  • 常量存储区

一, 语法

static data_type var_name = var_value;
#include<stdio.h> 
int fun() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("%d ", fun()); //1
  printf("%d ", fun()); //2
  return 0; 
}
#include<stdio.h> 
int fun() 
{ 
  int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("%d ", fun()); //1
  printf("%d ", fun()); //1
  return 0; 
}

静态变量就像全局变量一样,如果没初始化的话就是0,如下x打印0,但是y却被打印成1;所以c语言的初始化很重要,最好给初值

#include <stdio.h> 
int main() 
{ 
    static int x; 
    int y; 
    printf("%d  %d\n", x, y); // 0 , 1
}

静态变量初始化:可以给定一个常量,但是不能给方法,如下图会报错。

#include<stdio.h> 
int initializer(void) 
{ 
    return 50; 
} 

int main() 
{ 
    static int i = initializer(); 
    printf(" value of i = %d", i); 
    getchar(); 
    return 0; 
}
main.c:9:20: error: initializer element is not a compile-time constant
    static int i = initializer(); 
                   ^~~~~~~~~~~~~
1 error generated.

在c/c++中,static不仅可以修饰变量还可修饰方法。

在结构体中,不可使用static关键字

results matching ""

    No results matching ""