(1) while(i ++ == j ++)结束时发生什么
不等价与
-
while(i == j) {
-
i++;
-
j++;
-
}
而等价于
-
while(i == j) {
-
i++;
-
j++;
-
}
-
i++;
-
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修饰的变量到底是什么
实验:
-
int main()
-
{
-
const int b;
-
int c;
-
static int d;
-
printf("%p, %p, %p, %p\n ", &b, &c, "ab", &d);
-
return 0;
-
-
}
结果
Press ENTER or type command to continue
0x7fff24097018, 0x7fff2409701c, 0x400644, 0x601044
我的结论:
从上面的结果可以看出由const修饰的局部变量和普通的局部的变量被分到了同一块内存区域,静态变量被分到一块全局区域,而真正的常量“ab”被分到了另一区域。所以看出有const修饰的变量表示只读,其行为由编译器来保证。
(b)何时给const修饰的变量赋值
实验
-
struct test {
-
int a;
-
int b;
-
};
-
int main()
-
{
-
const struct test t1 = {.a = 1, .b = 2};
-
const int a = 1;
-
-
const struct test t2;
-
const int b;
-
t2.a = 1;
-
t2.b =2;
-
t2 = t1;
-
b = 2;
-
printf ("%d, %d\n", t1.a, t1.b);
-
printf ("%d, %d\n", t2.a, t2.b);
-
return 0;
-
}
结果:
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
-
struct test {
-
int b;
-
const int a;
-
};
-
int main()
-
{
-
struct test a = {.a = 2, .b =2};
-
printf("%d, %d\n", a.a, a.b);
-
return 0;
-
}
结果
可以编译通过,并且结构为2,2.
我的结论:
在结构体中的成员可以有const来修饰,同样的对这个成员的赋值必须在声明一个这个结构体类型的变量时同时赋值。
另外,结构体的成员不能赋值,也不能用static修饰。
struct test {int b; static int a;} 和struct test { int b; int a = 1}是不允许的 ;
阅读(2199) | 评论(0) | 转发(0) |