C语言——条件编译和static关键字

举报
yd_221104950 发表于 2020/12/03 00:05:39 2020/12/03
4.2k+ 0 0
【摘要】 条件编译 #include <stdio.h> #ifdef HELLO char *c = "hello world";//如果HELLO这个宏存在,包含这段代码 #else char *c = "No zuo,no die"; //否则包这段代码 #endif int main(){ printf("%s\n",c); return 0; } 12345...

条件编译

#include <stdio.h>

#ifdef HELLO 
 char *c = "hello world";//如果HELLO这个宏存在,包含这段代码
#else
 char *c = "No zuo,no die"; //否则包这段代码
#endif

int main(){ printf("%s\n",c); return 0;
}

  
 

static 关键字

程序想通过记住之前的值,然后不断叠加上去:

 #include <stdio.h> int count = 0; int counter(){ return ++count; } int main(){ printf("%d\n",counter()); printf("another:%d\n",counter()); return 0; }

  
 

再看一个例子,这个例子是说明全局变量,在其他源文件确实是可以访问到count的:
a.h

void hello();

  
 

a.c

#include <stdio.h>
#include "a.h"
int count = 100;
void hello(){ printf("%d \n",count);
}

  
 

test.c

#include <stdio.h>
#include "a.h"
//在使用在其他地方定义的全局变量,要先把它声明为外部变量
extern int count; 
int main(){ printf("@@@@%d\n",count); count = 111; hello(); return 0;
}

  
 

编译运行:

~/Desktop/Mcc$ gcc a.c test.c -o test
~/Desktop/Mcc$ ./test
@@@@100
111 

  
 

上述代码用了一个count的全局变量,因为count全局变量在全局作用域,所以其他函数都可以修改它的值。如果你在写一个大型程序,就需要小心控制全局变量的个数。因为它们可能导致代码出错。
好在C语言允许你创建只能在函数局部作用域访问的全局变量,如test1.c:

#include <stdio.h>
int counter(){
		//count虽然是全局变量,但它只能在函数内部访问,而static关键字表示将在counter()函数调用期间保持该变量的值 static int count = 0; return ++count;
}
int main(){ printf("%d \n",counter()); printf("%d \n",counter()); printf("%d \n",counter()); printf("%d \n",counter()); printf("%d \n",counter()); return 0;
}

  
 

编译运行:
~/Desktop/Mcc$ gcc test1.c -o test1
~/Desktop/Mcc$ ./test1
1
2
3
4
5

上面程序中的关键字static会把变量保存在存储器的全局变量区,但是当其他函数试图访问count变量时编译器会抛出错误。

用static定义私有变量或函数

**可以在函数外使用static关键字,它表示“只有这个.c文件中的代码能使用这个变量或函数。**如:
a.h

void hello();

  
 

a.c

#include "a.h"
#include <stdio.h>
static void  good_morning(char *msg);
static int count = 100;
void hello(){ printf("%d \n",++count); good_morning("Good morning!");
}
static void good_morning(char *msg){ printf("%s \n",msg);
}

  
 

test.c

#include <stdio.h>
#include "a.h"
int main(){ hello(); hello(); hello(); return 0;
}

  
 

编译运行:

~/Desktop/Mcc$ gcc a.c test.c -o test
~/Desktop/Mcc$ ./test
101 
Good morning! 
102 
Good morning! 
103 
Good morning! 

  
 

上面这个程序的static关键字是用来控制变量或函数的作用域,防止其他代码以意想不到的方式访问你的数据或函数。

文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_40763897/article/details/87867292

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。