星期五, 11月 01, 2013

同時轉型又宣告之神秘的 C

不但可以邊 casting 邊宣告,宣告玩之後還能繼續使用!
不過 gcc 跟 g++ 編譯器的行為不太一樣就是了,g++ 並不會直接給你過關。
code 寫久了,網上的技術文章逛久了,就會發現很多小惡魔小細節,是藏在編譯器裡面。




struct x { 
    int xx; 
};

int main()
{
    struct x data;
    data.xx = 99; 
    struct x *tmp = &data;

    printf("tmp->xx = %d \n", tmp->xx);
    printf("(!#$^&)->yy = %d \n", ((struct y {int yy;} *)(tmp))->yy);
    
    struct y xxxx; // Also can be used later!

    // Change *.cpp will have different result
    // gcc will select the correct back-end compiler based on file extension 
    // In c++: error: types may not be defined in casts

    return 0;
}