C语言中的static

原理

C语言中的static可用来改变变量的作用域和生存期和函数的作用域,该关键字可以用来修饰函数的定义和声明,和变量的定义。

用static修饰函数定义,表示该函数只在本文件有效(定义所在的文件),其它文件对该函数不可见。

用static修饰函数外的变量定义,表示该变量只在本文件有效(定义所在的文件),其它文件对该变量不可见。

用static修饰函数内的变量定义,表示该变量在屡次函数调用间1直有效。它的作用域依然是函数,但生存期是全部程序的生存期


用static修饰函数声明,表示该函数的定义只能在本文件


about声明和定义

如果定义先于使用,则不需要声明

当定义后于使用时,在使用之前声明


小实验

file1.cpp

#include<stdio.h> //static variable,used only in a file static int a; //static function,used only in a file static void f(void ){ a=1; printf(a=%d ,a); a=2; printf(a=%d ,a); } void ff(void){ f(); }

main.cpp

#include<stdio.h> //in f1.cpp,define a and f as static int a; void f(void){ printf(f() ); } void ff(void); extern void print(void); /***************************主函数***************************/ int main(){ print(); print(); print(); ff(); printf(a=%d ,a); f(); return 0; } void print(void){ static int n=0; if(n==0) { printf(the first time ); n=1; } else { printf(not the first time ); } printf(the address of n is : %X ,&n); }

实验结果



相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...