Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12955
  • 博文数量: 16
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 170
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-08 11:44
文章分类
文章存档

2014年(16)

我的朋友
最近访客

分类: C/C++

2014-05-02 17:12:50

(1) while(i ++ == j ++)结束时发生什么

点击(此处)折叠或打开

  1. while(i++ == j++);
不等价与

点击(此处)折叠或打开

  1. while(i == j) {
  2.     i++;
  3.     j++;
  4. }
而等价于

点击(此处)折叠或打开

  1. while(i == j) {
  2.     i++;
  3.     j++;
  4. }
  5. i++;
  6. j++;
因为当i != j时 i++; j++;依然会执行

(2) container_of
    #define container_of(pointer, type, member)  ((char *)pointer - offsetof(type, member)
pointer 被强制转换为(char *)的原因是对指针的加减一次移动的大小为类型大小,即sizeof(member).
    对于数组int a[10][10]. 
    a= a[0] = &a =&a[0]=&a[0][0] 都指向同一个地址,但是分别利用它们做加减的结果却并不相同。
    &a + 1 = sizeof(a)= 400
    a + 1 = &a[0] + 1 = 40
    a[0] + 1 = &a[0][0] + 1 = 4
(3) const

 (a) 用const修饰的变量到底是什么
实验:

点击(此处)折叠或打开

  1. int main()
  2. { 
  3.         const int b;
  4.         int c;
  5.         static int d;
  6.         printf("%p, %p, %p, %p\n ", &b, &c, "ab", &d);
  7.         return 0;

  8. }
结果
    Press ENTER or type command to continue
    0x7fff24097018, 0x7fff2409701c, 0x400644, 0x601044    
我的结论:
    从上面的结果可以看出由const修饰的局部变量和普通的局部的变量被分到了同一块内存区域,静态变量被分到一块全局区域,而真正的常量“ab”被分到了另一区域。所以看出有const修饰的变量表示只读,其行为由编译器来保证。

(b)何时给const修饰的变量赋值
  实验

点击(此处)折叠或打开

  1. struct test {
  2.         int a;
  3.         int b;
  4. };
  5. int main()
  6. {
  7.         const struct test t1 = {.a = 1, .b = 2};
  8.         const int a = 1;

  9.         const struct test t2;
  10.         const int b;
  11.         t2.a = 1;
  12.         t2.b =2;
  13.         t2 = t1;
  14.         b = 2;
  15.         printf ("%d, %d\n", t1.a, t1.b);
  16.         printf ("%d, %d\n", t2.a, t2.b);
  17.         return 0;
  18. }
结果:
test.c:15:2: error: assignment of member ‘a’ in read-only object
test.c:16:2: error: assignment of member ‘b’ in read-only object
test.c:17:2: error: assignment of read-only variable ‘t2’
test.c:18:2: error: assignment of read-only variable ‘b’
我的结论:
    从上面的结论可以看出,无论是基本数据类型(如int)还是复合数据类型(如struct),如果用const修饰的话必须在定义时对其赋值。
(3)struct中的const

点击(此处)折叠或打开

  1. struct test {
  2.         int b;
  3.         const int a;
  4. };
  5. int main()
  6. {
  7.         struct test a = {.a = 2, .b =2};
  8.         printf("%d, %d\n", a.a, a.b);
  9.         return 0;
  10. }
结果
    可以编译通过,并且结构为2,2.
我的结论:
    在结构体中的成员可以有const来修饰,同样的对这个成员的赋值必须在声明一个这个结构体类型的变量时同时赋值。
另外,结构体的成员不能赋值,也不能用static修饰。struct test {int b;   static int a;} 和struct test { int b;   int a = 1}是不允许的 ;














阅读(2199) | 评论(0) | 转发(0) |
0

上一篇:kmp

下一篇:BM

给主人留下些什么吧!~~