Print “Hello World” with empty or blank main in C++

C++Server Side ProgrammingProgramming

In this problem we will see how to print “Hello World” into the console, but we cannot write anything into the main function.

This problem can be solved in two different ways. In the first approach we will create a global variable, then we will store the returned value of printf() function into that variable. When printf() is executed, then it will be printed. See the code for better understanding.

Example

 Live Demo

#include<iostream>
using namespace std;
int a = printf("Hello World");
int main() {
}

Output

Hello World

In the next approach we will create a class, and print the line using the constructor of that class. Then create an object of that class at the global section. So when the object is created, it will call the constructor automatically, and the line will be printed.

Example

 Live Demo

#include<iostream>
using namespace std;
class my_class {
   public:
   my_class() {
      cout << "Hello World";
   }
};
my_class my_obj;
int main() {
}

Output

Hello World
raja
Published on 02-Apr-2019 14:06:25
Advertisements