c - c中函数和变量的静态作用域使用

标签 c syntax static

C 编程语言一书描述了静态变量的用法,主题what-does-static-mean-in-a-c-program

  1. A static variable inside a function keeps its value between invocations.
  2. A static global variable or a function is "seen" only in the file it's declared in

和书上解释的一样,但是第1点可以,第2点不可以。

我的代码:

标题.h

static int VAL = 15;
int canShare = 1;

static void hello(char c) {
printf("header file -> VAL: %d\n", VAL);
printf("header file -> canShare: %d\n", canShare);

printf("hello func -> %d\n", c);
}

主程序

#include <stdio.h>
#include "header.h"

main() {

printf("main -> VAL: %d\n", VAL+1);
printf("main -> canShare: %d\n", canShare+1);

hello('A');
}

输出

main -> VAL: 16
main -> canShare: 2
header file -> VAL: 15
header file -> canShare: 1
hello func -> 65

最佳答案

解释中存在细微的错误:

A static global variable or a function is "seen" only in the file it's declared in.

它仅在声明的翻译单元中可用。#include 指令字面上将头文件包含到翻译单元中,因此 TU 包含包含的头文件(如你可能会期望,语法上)。

关于c - c中函数和变量的静态作用域使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928328/

相关文章:

c - 二进制搜索给我一个段错误

c - 通过宏将变量声明为内联函数

c - ADC 中断未被调用

php - include ('file.php' ) 和 include 'file.php' 有什么区别

c++ - 在一个函数中静态初始化多个静态变量

performance - Apache 在 Tomcat 之前安装,有什么好处?

c - 如何将一个句子复制到一个字符数组中

java - ASP 到 Java/JSP

flutter - Dart 中获取/设置属性的正确语法是什么?如何记住属性语法?

javascript - ASP.NET:UpdateProgress 不适用于具有 ClientIDMode ="Static"的控件