《OOC》笔记(1)——C语言const、static和extern的用法

时间:2021-06-19 12:25:26

《OOC》笔记(1)——C语言const、static和extern的用法

C语言中const关键字用法不少,我只喜欢两种用法。一是用于修饰函数形参,二是用于修饰全局变量和局部变量。

用const修饰的函数形参

直接修饰

一个形如

int Minus(const int a, const int b, int testCase);

的函数,const的意义是什么呢?

答:参数a被const修饰,说明在Minus函数内,编译器不允许a被别的变量(例如x)赋值(修改)。参数b同理。

如果你写了a = x; 这样的语句,编译器会警告"warning: assignment of read-only location",即"警告:赋值到只读位置"。

 int Minus(const int a, const int b, int testCase)
{
int x, y;
switch (testCase)
{
case :
a = x; //warning: assignment of read-only location
b = y; //warning: assignment of read-only location
break;
case :
a = (const int)x; //warning: assignment of read-only location
b = (const int)y; //warning: assignment of read-only location
break;
case :
x = a; //OK with compiler.
y = b; //OK with compiler.
break;
case :
x = (int)a; //OK with compiler.
y = (int)b; //OK with compiler.
break;
default:
break;
}
int result = a - b;
return result;

指针修饰

请原谅这个不靠谱的的叫法吧。总之,一个形如

int Add(const int * a, const int * b, int testCase);

的函数,const的意义是什么呢?

答:参数a是指向int的指针,a被const修饰,说明在Add函数内,a指向的内容不能被赋值(修改)。如果将a赋值给另一个int*类型的指针x,那么就可以通过x修改a指向的内容。这违反了const的作用。因此,编译器禁止将a赋值给别的变量。参数b同理。

如果你写了x = a; 这样的语句,编译器会警告"warning: assignment discards qualifiers from pointer target type",即"警告:赋值无视目标指针的修饰符"。

 int Add(const int * a, const int * b, int testCase)
{
int * x;
int * y;
switch (testCase)
{
case :
a = x; //OK with compiler.
b = y; //OK with compiler.
break;
case :
a = (const int *)x; //OK with compiler.
b = (const int *)y; //OK with compiler.
break;
case :
x = a; //warning: assignment discards qualifiers from pointer target type
y = b; //warning: assignment discards qualifiers from pointer target type
break;
case :
x = (int *)a; //OK with compiler, but const fade out.
y = (int *)b; //OK with compiler, but const fade out.
break;
case :
*a = *x; //warning: assignment of read-only location
*b = *y; //warning: assignment of read-only location
case :
*x = *a; //OK with compiler, but const fade out.
*y = *b; //OK with compiler, but const fade out.
default:
break;
}
int result = *a + *b;
return result;
}

总结以上两种情况,就是"当const修饰一个普通变量时,则这个普通变量不应被修改。当const修饰一个指针变量时,这个指针指向的内容不应被修改,也不应让其它指针指向这个内容。"

用const修饰全局变量和局部变量的思想同上。

用static修饰的函数和变量

如果在头文件x.h中声明的函数和变量如下

extern static int startPoint;
static int Add(int a, int b);

在源文件x.c中定义如下

 static int startPoint = ;
static int Move(int a)
{
return startPoint + a;
}

那么这个Move函数就只能在x.c这个源文件中使用。这相当于面向对象里的class里的私有函数了。

用static修饰的变量startPoint,也只能在x.c这个源文件中使用,这相当于面向对象里的class里的私有静态变量。

同时,这里也显示了extern用于声明全局变量的方法。首先在头文件x.h里用extern修饰该变量的声明部分,然后在源文件x.c中定义该变量。

在x.h和x.c里的示例中,我们同时用extern和static修饰了全局变量startPoint,那么这个startPoint变量就只能在源文件x.c中出现了。如果去掉static,那么startPoint就能够在所有写了"include "x.h""的源文件中使用了。