都忘了曾看過在某地下論壇裡看過這經典的題目。題目是給定下面的程式碼,這段程式碼不能動,最後輸出結果要變成 Hello, World

 

int main()
{
    cout << "World";
    return 0;
}

 

當時 C++ 程度比現在還差,本來呈現放棄狀態,後來想五分鐘之後突然有種莫名的想法..

 

[1] Kuso Solution

 

#include <cstdio>
int main() 
{
    printf("Hello, World");
    return 0;
}

#if 0
/* 
int main()
{
    cout << "World";
    return 0;
}
*/
#endif

 

 其實就只是 comment 掉而已,不知別人收到會有什麼想法,再過五分鐘後,又想到 C++ 有其他方式亂搞。

 

[2] global variable initialize

 

#include <iostream>
#include <cstdlib>
using namespace std;

int before_main() 
{
    printf("Hello, World");
    getchar();
    exit(EXIT_SUCCESS);
    return 1;
}
int garbge = before_main();
int main()
{
    cout << "World" ;
    return 0;
}

 

 由於 C macro 看了不少,隔了五分鐘,又生了第三個答案出來,我想面試的人看到應該會想砍人。

 

[3] macro solution

 

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout << "Hello, World";
    return 0;
}

#define main garbge
int main()
{
    
    cout << "World" ;
    return 0;
}

 

雖想出了三個 solution ,到現在還在想,如果真的是面試的話,可能一個 solution 都不敢放上去 Orz。

後來在網路上搜尋時,發現原來這題很受歡迎,而且不只我一個人想到這些解法,很多人都利用了 preprocessor 及 macro 重定義方式下去解 (感覺好像是 要死大家一起死 )。日後再念 C++ 時,大概知道這題面試要求可能是要  global overload operator <<  這種作法。

 

#include <iostream>
#include <cstdio>

class ostream{
public:
    void operator << (const char* str) const
    {
        printf("Hello, %s", str);
    }
}cout;

int main()
{    
    cout << "World" ;
    return 0;
}

 

 較正規 C++ 方式我認為應該還有其他作法便是了。有興趣可再上網查一下。

 

arrow
arrow
    全站熱搜

    edisonx 發表在 痞客邦 留言(2) 人氣()