문제

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.

도움이 되었습니까?

해결책

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;
    

다른 팁

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

int main()
{
}
  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() { }
    
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top