当前位置: 当前位置:首页 >数据库 >C语言迷惑行为大赏正文

C语言迷惑行为大赏

作者:IT科技类资讯 来源:IT科技类资讯 浏览: 【】 发布时间:2025-11-05 11:18:10 评论数:

代码0:

#include<stdio.h> int main(void) {     int c = 5;     switch(c)     {         case 0 ... 10:             printf("0-->10n");             break;         case 11 ... 20:             printf("11-->20n");             break;         default:             printf("othern");     }     return 0; } 

输出结果:

0-->10 

以上特性被常见编译器支持,语言迷但是惑行标准中并未提到。

代码1

#include<stdio.h> int main(void) {     printf("%mn");     return 0; } 

输出结果:

Success 

等价于:

printf("%s\n",语言迷stderr(errno)); 

由于你的代码前面并没有执行出错设置errno,因此errno会是惑行0,而对应的语言迷描述信息就是Success。

代码2

#include<stdio.h> int main(void) {     int i = 10;     printf("%zun",惑行sizeof(i++));     printf("%zun",sizeof(++i));     printf("%dn",i);     return 0; } 

输出结果:

4 4 10 

sizeof实际作用的对象是类型。sizeof中的高防服务器语言迷表达式本身并不会被执行。

代码3

#include <stdio.h> #include <unistd.h> int main(void)   {     while(1)     {         fprintf(stdout,惑行"公众号");         fprintf(stderr,"编程珠玑");         sleep(10);     }     return 0; } 

输出结果:

编程珠玑编程珠玑编程珠玑 

为什么不会输出公众号呢?原因在于标准输入默认是行缓冲,而标准错误是语言迷无缓冲。这在《那些奇奇怪怪的惑行缓冲问题》中已经有解释了。

代码4

#include <stdio.h> int main(void)   {     int a = 10;     switch(a)     {         int b = 20;         case 10:             printf("%dn",语言迷a + b);             break;         default:             printf("%dn",a + b);             break;     }     return 0; } 

输出结果:

10 

switch中的int b = 20,并不会被执行,惑行你编译时就会发现有警告。语言迷

代码4

#include <stdio.h> int main(void)   {     printf("%cn",惑行4["hello 公众号编程珠玑"]);     return 0; } 

输出结果:

等价于:

char *str = "hello 公众号编程珠玑"; printf("%c\n",str[4]); 

代码5

//来源:公众号编程珠玑 //https://www.yanbinghu.com #include<stdio.h> int main(void) {     char arr[] = {h,e,l,l,o};     printf("%s\n",arr);//灾难!,服务器租用语言迷可能会崩溃     return 0; } 

代码6

没啥用,还会core dump的超短代码,可以编译运行:

main=0; 

代码7

#include<stdio.h> int main(void) {     int arr[] = {5,4,3,2,1};     for(int i = -1; i < sizeof(arr)/sizeof(int) - 1; i++)     {         printf("%dn",arr[i+1]);     }     printf("end\n");     return 0; } 

输出结果:

end 

原因也很简单,sizeof(arr)/sizeof(int)的结果是unsigend, int类型的i 和unsigned比较,被转换为一个很大的unsigned数,所以for循环的条件不满足。b2b供应网

代码8

#include<stdio.h> test() {     long b = 12345678987654321;     return b; } int main(void) {     long a = test();     printf("%ldn",a);     return 0; } 

输出结果:

1653732529 

代码9

#include<stdio.h> int main(void) {     float a = 3;     int b = 2;     printf("%dn",a/2);     return 0; } 

输出结果:

1199094392 

原因:浮点数在计算机中按照IEEE754标准存储

最近更新

点击排行