C語言迷惑行為大賞
代碼0:
- #include<stdio.h>
- int main(void)
- {
- int c = 5;
- switch(c)
- {
- case 0 ... 10:
- printf("0-->10\n");
- break;
- case 11 ... 20:
- printf("11-->20\n");
- break;
- default:
- printf("other\n");
- }
- return 0;
- }
輸出結果:
- 0-->10
以上特性被常見編譯器支持,但是標準中并未提到。
代碼1
- #include<stdio.h>
- int main(void)
- {
- printf("%m\n");
- return 0;
- }
輸出結果:
- Success
等價于:
- printf("%s\n",stderr(errno));
由于你的代碼前面并沒有執(zhí)行出錯設置errno,因此errno會是0,而對應的描述信息就是Success。
代碼2
- #include<stdio.h>
- int main(void)
- {
- int i = 10;
- printf("%zu\n",sizeof(i++));
- printf("%zu\n",sizeof(++i));
- printf("%d\n",i);
- return 0;
- }
輸出結果:
- 4
- 4
- 10
sizeof實際作用的對象是類型。sizeof中的表達式本身并不會被執(zhí)行。
代碼3
- #include <stdio.h>
- #include <unistd.h>
- int main(void)
- {
- while(1)
- {
- fprintf(stdout,"公眾號");
- fprintf(stderr,"編程珠璣");
- sleep(10);
- }
- return 0;
- }
輸出結果:
- 編程珠璣編程珠璣編程珠璣
為什么不會輸出公眾號呢?原因在于標準輸入默認是行緩沖,而標準錯誤是無緩沖。這在《那些奇奇怪怪的緩沖問題》中已經(jīng)有解釋了。
代碼4
- #include <stdio.h>
- int main(void)
- {
- int a = 10;
- switch(a)
- {
- int b = 20;
- case 10:
- printf("%d\n",a + b);
- break;
- default:
- printf("%d\n",a + b);
- break;
- }
- return 0;
- }
輸出結果:
- 10
switch中的int b = 20,并不會被執(zhí)行,你編譯時就會發(fā)現(xiàn)有警告。
代碼4
- #include <stdio.h>
- int main(void)
- {
- printf("%c\n",4["hello 公眾號編程珠璣"]);
- return 0;
- }
輸出結果:
- o
等價于:
- 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("%d\n",arr[i+1]);
- }
- printf("end\n");
- return 0;
- }
輸出結果:
- end
原因也很簡單,sizeof(arr)/sizeof(int)的結果是unsigend, int類型的i 和unsigned比較,被轉(zhuǎn)換為一個很大的unsigned數(shù),所以for循環(huán)的條件不滿足。
代碼8
- #include<stdio.h>
- test()
- {
- long b = 12345678987654321;
- return b;
- }
- int main(void)
- {
- long a = test();
- printf("%ld\n",a);
- return 0;
- }
輸出結果:
- 1653732529
代碼9
- #include<stdio.h>
- int main(void)
- {
- float a = 3;
- int b = 2;
- printf("%d\n",a/2);
- return 0;
- }
輸出結果:
- 1199094392
原因:浮點數(shù)在計算機中按照IEEE754標準存儲