2013-10-09 65 views
-4

回報是編寫以下要求程序主持會議的方式:「Hello World」的你好世界上僅有的在主

  1. 打印標準輸出
  2. 具有空主要(只是返回0),即

    int main(int argc, char** argv) { 
        return 0; 
    } 
    
  3. main必須包含沒有額外的代碼除了上面。

+0

http://stackoverflow.com/questions/10897552/call-a- function-before-main?lq = 1 – chris

+0

歡迎來到SO。這個想法是,你試圖自己解決這個問題,當你遇到一個特定的問題時,你會問一個問題,顯示相關的代碼。 – juanchopanza

+2

使用谷歌搜索「Hello World」C給了我37,000,000次點擊。他們都沒用嗎? – Bathsheba

回答

14

你可以用不同的方法做到這一點。考慮你有#include <iostream>然後下面的方法應該放在main之前。

  1. 您可以使用宏,但結果未定義,如註釋中注意到的那樣。所以即使這是一個簡單的方法,它也不應該被使用。爲了完整性,我仍然將其留在這裏。

    #define return std::cout << "Hello world!"; return 
    
  2. 你可以使用靜態變量:

    int helloWorld() 
    { 
        std::cout << "Hello World"; 
        return 0; 
    } 
    static int print = helloWorld(); 
    
  3. ...或者更簡單:

    bool printed = std::cout << "Hello World"; 
    
  4. 你可以做同樣的與對象:

    struct hello 
    { 
        public: 
         hello() 
         { 
          std::cout << "Hello, world!"; 
         } 
    } world; 
    
+0

+1非常具有啓發性。 – opalenzuela

+2

請注意,選項1的行爲未定義。 –

+0

@PeteBecker,好點,會更新。 – sukhmel

1
struct Bob 
{ 
    Bob() 
    { 
     printf("Hello world!"); 
    } 
} bob; 

int main() 
{ 
} 
0
  1. 對象實例化:

    struct S 
    { 
        S() { std::cout << "Hello World!"; } 
    } s; 
    
    int main() { } 
    
  2. 或通過表達式:

    int i = ((std::cout << "Hello World\n"), 5); 
    
    int main() { }