-4

What is the way to write a program meeting following requirements:

  1. Prints "Hello world!" to stdout;
  2. Has empty main (just returning 0) i.e.

    int main(int argc, char** argv) {
        return 0;
    }
    
  3. main must contain no additional code except for that above.

  • http://stackoverflow.com/questions/10897552/call-a-function-before-main?lq=1 – chris Oct 09 '13 at 13:37
  • Welcome to SO. The idea is that you try to solve this yourself, and when you encounter a specific problem, you ask a question, showing relevant code. – juanchopanza Oct 09 '13 at 13:38
  • 2
    Googling "Hello World" C gave me 37,000,000 hits. Were they all useless? – Bathsheba Oct 09 '13 at 13:38
  • You might want to clarify the requirement that you print the text without any code in main, as many will not spot that. – Neil Kirk Oct 09 '13 at 13:41
  • 1
    @NeilKirk so I did. I guess, I'll just accept what seems best answer and be more constructive next time. – user2862943 Oct 09 '13 at 13:46
  • @Bathsheba: It might take quite a while to read through 37,000,000 examples to discover whether any of them have an empty `main`. – Mike Seymour Oct 09 '13 at 13:52

3 Answers3

14

You can do this in different ways. Consider you have #include <iostream> then following methods should be placed before main.

  1. You may use macros, but the result is undefined as noticed in comments. So even if this is an easy way, it should never be used. I will still leave it here for completeness.

    #define return std::cout << "Hello world!"; return
    
  2. You may use static variable:

    int helloWorld() 
    { 
        std::cout << "Hello World"; 
        return 0; 
    }
    static int print = helloWorld();
    
  3. ... or even simpler:

    bool printed = std::cout << "Hello World";
    
  4. You can do same with object:

    struct hello
    {
        public:
            hello()
            {
                std::cout << "Hello, world!";
            }
    } world;
    
sukhmel
  • 1,402
  • 16
  • 29
1
struct Bob
{
    Bob()
    {
        printf("Hello world!");
    }
} bob;

int main()
{
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
0
  1. Object Instantiation:

    struct S
    {
        S() { std::cout << "Hello World!"; }
    } s;
    
    int main() { }
    
  2. Or in an expression:

    int i = ((std::cout << "Hello World\n"), 5);
    
    int main() { }
    
David G
  • 94,763
  • 41
  • 167
  • 253