Linux 内核C语言深度解析 复习笔记

一.
在 GNU C 中,通过数组元素索引,我们就可以给某个指定的元素直接赋值

#include <stdio.h>

int main(){
        int a[100] = {[10]=1, [20]=2, [30]=3};
        for(int i = 1;i <= 3;i++){
                printf("%d\n", a[i*10]);
        }
        return 0;
}
/*output:
1
2
3
*/
~         

二.
GNU C 支持使用 … 表示范围扩展,这个特性不仅可以使用在数组初始化中,也可以使用在switch-case 语句中。

实验代码:

#include <stdio.h>
#include <string.h>

void print(int count, ...){
        int *p = &count - 1;
        printf("count_addr: %p\n", &count);
        for(int i = 0;i < count;i++){
                printf("%d\n", *p);
                p -= 1;
        }
}

int main(int argc, char *argv[]){
        int a[100] = { [0 ... 9]=7, [10 ... 19]=7 };
        print(4, 1, 2, 3, 4);
        for(int i = 0;i < 21;i++){
                if(a[i]){
                        printf("%d",a[i]);
                }
                if((i+1) % 10 == 0)
                        putchar('\n');
        }
        return 0;
}
/*output:
count_addr: 0x7ffd34346a2c
1152
32696
-68417024
21873
7777777777
7777777777
*/

看到这输出 有点莫名奇妙,然后用gdb 调试跟进print函数去看参数在栈上的分配情况,然后我傻了

****
count参数跟其他传进print的参数的地址不连续…, 靠count的指针无法输出其他参数,64位是这个结果,不清楚32位可不可以正确输出,如果把 void print(int count, …), 改成void print(int count, int a, int b, int c, int d) 就可以正确输出…

三——语句表达式
语句表达式的定义:
GNU C 是对 C标准作了扩展,允许在一个表达式里内嵌语句, 允许在表达式内部使用局部变量,for循环和goto跳转语句。这样的表达式,我们称之为语句表达式。

语句表达式的值总等于最后一个表达式的值。

( { 表达式1;表达式2;表达式3;} )

实验程序

#include <stdio.h>

int main(int argc, char *argv[]){
        char *s = "This is a test", *s2 = NULL;
        s2 = ({
                1;
                2;
                3;
                s;
                });
        if(s2)
                puts(s2);
        return 0;
}
/*output:
This is a test
*/

其他C语言的巧妙用法还是看 体验课复习吧,内容太多了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值