关键字

简介: 可用在局部变量 全局变量 函数

目录

static

extern

define 宏

static

可用在局部变量 全局变量 函数

1.局部变量

void test()//进函数a生命周期开始
{
   int a = 1;//a局部变量,再进来a还是1,循环往复
  a++;//2
  printf("%d", a);//2222222222
}//出函数a就销毁了还给操作系统
int main()
{
  int i = 0;
  while (i < 10)
  {
    test();
    i++;
  }
  return 0;
}
#include <stdio.h>
int sum(int a)
{
    int c = 0;
    static int b = 3;
    c += 1;
    b += 2;
    return (a + b + c);
}
int main()
{
    int i;
    int a = 2;
    for (i = 0; i < 5; i++) 
    { 
        printf("%d,", sum(a)); 
    } 
} 

image.png


a
b c
0 2 5 1
1 2 7 1
2 2 9 1
3 2 11 1
4 2 13 1

image.png

void test()
{
  static int a = 1;//上一次出的时候a没有销毁,可以根据结果推测,每一次调用test函数使用的a是上一次留下的,
  a++;//2
  printf("%d", a);//234567891011
}
int main()
{
  int i = 0;
  while (i < 10)
  {
    test();
    i++;
  }
  return 0;
}


image.png

在另一个文件定义的变量不能直接使用,要声明
test.c
#include<stdio.h>
extern int g;//使用之前声明,extern是一个关键字,专门用来声名外部符号的
int main()
{
  printf("%d", g);//10
  return 0;
}
g是main.c另一个文件中定义的全局变量
int g=10;

同理修饰函数和修饰全局变量也是一样的

extern int add(int a, int b);
int main()
{
  int a = 10, b = 20;
  add(a, b);
  return 0;
}
//test.c里面的
int add(int a, int b)
{
  return a + b;
}

define定义宏

//定义宏
#define add(a,b)((x)+(y))
int main()
{
  int a = 10, b = 20;
  add(a, b);
  return 0;
}
相关文章
|
1月前
|
存储 程序员 编译器
C++-关键字
C++-关键字
27 1
|
7月前
|
存储 算法 编译器
带你了解并掌握一些C++关键字的使用
带你了解并掌握一些C++关键字的使用
62 0
|
19天前
|
Java API
RentrantLock关键字详解
RentrantLock关键字详解
|
1月前
|
Java
|
1月前
|
C++
|
10月前
|
Java
关键字this
关键字this
31 0
单链表删除第一次关键字
删除第一次出现关键字为key的节点
|
编译器 程序员 C++
C++关键字之fallthrough
C++关键字之fallthrough
332 0
|
JavaScript 前端开发
29、this 关键字
this关键字是一个非常重要的语法点。毫不夸张地说,不理解它的含义,大部分开发任务都无法完成。
115 0
|
SQL XML 安全