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

条件编译

#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/weixin_40763897/article/details/87867292
今日推荐