关键字(static const volatile extern sizeof)

static、const、volatile、extern关键字的作用:
一、static
1、修饰存储类型使之成为静态存储类型
2、修饰链接属性使之成为内部链接属性
二、const
1、声明常变量,使声明的变量不能被修改
const int *ptr; //ptr为指向整型常量的指针,ptr的值可以修改,不能改变其所指向的值
int *const ptr; //ptr为指向整型的指针常量,ptr的值不能修改,能修改所指向的值
2、修改函数形参,使得形参在函数内不能被修改。

例:

/////////////////////////////////////////////////////////////////////////////////////////////////////

#include <stdio.h>

const int val=4;

void ptr(const int val)
{
val=1;
printf("%d ",val);
}

void main()
{
ptr(4);
}

编译结果:

test.c: In function 'ptr':
test.c:7: error: assignment of read-only location 'val'

/////////////////////////////////////////////////////////////////////////////////////////////////////

3、修饰函数返回值,使得函数的返回值不能被修改
const int getint(void);
则:const init= a=getint();

三、volatile
volatile指定的变量可能被系统、硬件、进程等改变,所以强制编译器每次从内存中取得该
变量的值,而不是从被优化后的寄存器中读取。
四、extern
1、修饰变量或函数,表明变量或函数在别的文件中定义的,提示编译器在其他文件中寻找。
例:
/////////////////////////////////////////////////////////////////////////////////////////////////////
test.c:
#include <stdio.h>
#include "test.h"

void main()
{
printf("%d ",func(10,5));
}

test.h:
extern int func(a,b); //暗示func函数在别的文件中定义

te.c:
int func(a,b)
{
return(a+b);
}

编译test.c、te.c文件:
gcc -c test.c
gcc -c te.c
连接目标文件:
gcc -o test test.c te.c

运行结果:
15
/////////////////////////////////////////////////////////////////////////////////////////////////////
2、extern "c"---实现C++代码调用其它C语言代码。加上extern "c"会指示编译器这部分代
码按C语言的编译方式进行编译,而不是C++。
五、sizeof
sizeof是在编译阶段处理,且不能被编辑为机器码,sizeof的返回值类型为size_t。sizeof
的结果等于类型或对象所占内存的字节数。
数组:int a[10] //sizeof(a)=4*10;
结构体:
(参考http://blog.csdn.net/jk110333/article/details/19237969和
http://www.cnblogs.com/fengfenggirl/p/struct_align.html)
struct s{
int a;
char ch;
short cs;
}s1; //sizeof(s1)=8;
int a;需要4字节
char ch;需要1字节
short cs;需要2字节
两部分对齐,向最长的4字节看齐:
int a;分配4字节(浪费0)
char ch和short cs;总共分配4字节(浪费1)
例:
/////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>

struct s{
int a;
char ch;
short cs;
}s1;
void main()
{
int a=1;
char c='a';

printf("sizeof(a):%d ",sizeof(a));
printf("sizeof(c):%d ",sizeof(c));
printf("sizeof(s1):%d ",sizeof(s1));
}
结果:
sizeof(a):4
sizeof(c):1
sizeof(s1):8
/////////////////////////////////////////////////////////////////////////////////////////////////////
sizeof(void)=1;
sizeof(void *)=4;

原文地址:https://www.cnblogs.com/Mr-Wenyan/p/7237124.html