2013-08-22 16:07:35
第五课 - const和volatile分析
const修饰变量---原来const不是真的常量
在C语言中const修饰的变量是只读的,其本质还是变量
const修饰的变量会在内存占用空间
本质上,const只对对编译器有用,在运行时无用
const修饰数组
在C语言中const修饰的数组是只读的
const修饰的数组空间不可被改变1 const int A[5] = {1,2,3,4,5};
2 int* p = (int*)A; 3 4 int i = 0; 5 6 for( i = 0;i<5;i++) 7 { 8 p[i] = 5-i; //oops!!
9 }
2013-08-22 16:07:35
第五课 - const和volatile分析
const修饰变量---原来const不是真的常量
在C语言中const修饰的变量是只读的,其本质还是变量
const修饰的变量会在内存占用空间
本质上,const只对对编译器有用,在运行时无用
1 #include<stdio.h> 2 #include<malloc.h> 3 /*通过指针,修改const定义的“常量”*/ 4 int main() 5 { 6 const int cc = 1; 7 int* p = (int*)&cc; 8 printf("%d\n",cc); 9 10 *p = 3; 11 12 printf("%d\n",cc); 13 14 return 0; 15 }
const修饰数组
在C语言中const修饰的数组是只读的
const修饰的数组空间不可被改变
1 const int A[5] = {1,2,3,4,5};
2 int* p = (int*)A;
3 int i = 0;
4 for( i = 0;i<5;i++)
5 {
6 p[i] = 5-i; //oops!!
7 }
const修饰数组
const int* p;
int const* p;
int* const p;
const int* const p;
口诀:左数右指
当const出现在*号左边时指针指向的数据为常量
当const出现在*后右边时指针本身为常量
const修饰函数参数和返回值
const修饰函数参数表示在函数体内不希望改变参数的值
const修饰函数返回值表示返回值不可改变, 多用于返回指针的情形
1 const int* func()
2 {
3 static int count = 0;
4 count++;
5 return &count;
6 }
深藏不漏的volatile
volatile可理解为"编译器警告指示子字"
volatile用于告诉编译器必须每次去内存中取变量值
volatile主要修饰可能被多个线程访问的变量
volatile也可以修饰可能被未知因数更改的变量
int obj = 10;
int a = 0;
int b = 0;
a = obj;
sleep(100);
b = obj;
编译器在编译的时候发现obj没有被当成左值使用,会因此“聪明”的直接将obj替换成10,而把a和b都赋值为10。
课后思考
const和volatile是否可以同时修饰一个变量
const和volatlie int i = 0;这个时候i具有什么属性?编译器如何处理这个变量。
如果一个变量不会被本程序改变,通常可能给它加上const,但如果该变量可能被其他程序改变而本程序又在检测这个变量的值,就需要给它加上volatile,于是变量就同时有volatile和const了
2013年8月23日 09:13:49
第6课 - struct和union分析
空结构体占用多大内存?
下面的程序输出什么?
struct D
{
}
int main()
{
struct D d1;
struct D d2;
printf("%d\n",sizeof(struct D));
printf("%d,%0X\n",sizeof(d1),&d1);
printf("%d,%0X\n",sizeof(d2),&d2);
return 0;
}
由结构体产生柔性数组
柔性数组即数组大小待定的数组
C语言中结构体的最后一个元素可以是大小未知的数组
C语言中可以由结构体产生柔性数组
struct SoftArray
{
int len;
int array[];
}
union和struct的区别
struct中的每个域在内存中都独立分配空间
union只分配最大域的空间,所有域共享这个空间
struct A
{
int a;
int b;
int c;
}
union B
{
int a;
int b;
int c;
}
int main()
{
printf("%d\n",sizeof(struct A)); //12
printf("%d\n",sizeof(union B)); //4
return 0;
}
union的使用
union的使用受系统大小端的影响
union C
{
int i;
char c;
}
union C c
c,i = 1;
printf("%d\n",c.c);