初始化
int a[100] = { [10] = 1,[20] = 3 }; //指定位置初始化
int b[100] = { [1 ... 10] = 1, [15 ... 20] = 5 }; //指定范围初始化
int index;
switch (index) {
case 1:
printf("1\n");
break;
case 2 ... 8: //指定范围
printf("2-8\n");
break;
default:
printf("other: %d\n",index);
break;
}
Test t = { //结构体指定成员初始化
.age = 10,
.name = "actarjan"
};
语句表达式
语句表达式的值为最后一个表达式的值
int sum = 0;
sum = ({
int s = 0;
for ( int i = 1; i < 10; i++)
s += i;
s; //sum等于s
});
printf("sum = %d\n",sum); //sum = 45
宏中的语句表达式
#define MAX(x,y) x > y ? x : y //MAX(1!=1,1!=2);
#define MAX(x,y) (x) > (y) ? (x) : (y) //3 + MAX(1,2)
#define MAX(x,y) ((x) > (y) ? (x) : (y)) //MAX(i++,j++)
#define MAX(x,y) ({ \
int _x = x; \
int _y = y; \
_x > _y ? _x : _y; \
})
#define MAX(type,x,y) ({ \
type _x = x; \
type _y = y; \
_x > _y ? _x : _y; \
}) //调用: MAX(int,3,4)
#define MAX(x,y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y); \ //不同指针类型的比较会有一个警告,(void)用来消除运算结果没有使用的警告
_x > _y ? _x : _y; \
})
typeof与container_of宏
//typeof用于获取变量类型
int a;
typeof(a) b; //等价于int b
//container_of可根据成员变量地址获取结构体首地址
#define offsetof(TYPE,MEMBER) ((size_t) &((TYPE*)0)->MEMBER)
#define container_of(ptr,type,member) ({ \
const typeof( ((type *)0)->member ) *_mptr = (ptr); \
(type*) ( (char*)_mptr - offsetof(type,member) ); \
})
typedef struct {
int id;
int age;
} Test;
int main() {
Test t;
Test* ptr;
ptr = container_of(&t.age,Test,age);
printf("%p\n",&t);
printf("%p\n",ptr); //与&t相等
}
零长度数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int len;
char a[0];
} Test;
int main() {
printf("%lld\n",sizeof(Test)); //4
Test *t = (Test*)malloc(sizeof(Test) + 20);
t->len = 20;
strcpy(t->a,"hello world!\n");
printf("%s",t->a); //hello world!
free(t->a);
return 0;
}
__attribute__
/*
packed:不按字节对齐(或者说是按1字节对齐),减少内存空洞
aligned(x):按x字节对齐,x必须是2的整数幂,一般不超过16,太大不生效,
section:指定编译时所处的section
*/
typedef struct {
char a;
short b;
int c;
} Data __arrtibute__((packed,aligned(8))); //成员变量不对齐,整个结构体按8字节对齐
//sizeof(Data) = 8
529



被折叠的 条评论
为什么被折叠?



