來源:公衆號【編程珠璣】

作者:守望先生

ID:shouwangxiansheng

代碼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));

由於你的代碼前面並沒有執行出錯設置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",10);
    return 0;
}

輸出結果:

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("%d\n",a + b);
            break;
        default:
            printf("%d\n",a + b);
            break;
    }
    return 0;
}

輸出結果:

switch中的int b = 20,並不會被執行,你編譯時就會發現有警告。

代碼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比較,被轉換爲一個很大的unsigned數,所以for循環的條件不滿足。

代碼8

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

輸出結果:

代碼9

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

輸出結果:

原因:浮點數在計算機中按照IEEE754標準存儲

關注公衆號【編程珠璣】,獲取更多Linux/C/C++/數據結構與算法/計算機基礎/工具等原創技術文章。 後臺免費獲取經典電子書和視頻資源

相關文章