
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Hello World with Empty or Blank Main in C++
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 different ways. Initially, we will create a global variable, then we will store the returned value of the printf() function into that variable. When printf() is executed, then it will be printed.
You can print "Hello World" without using the logic inside the main() function in different ways, such as using Global Constructors,Class Object and macros, or preprocessor, etc.
Using Global Constructor
A global constructor is the constructor of a global object that runs before main(). If you add a print statement inside this constructor, it will be executed when the object is created, allowing you to print "Hello World" even with an empty main() function.
Syntax
Following is the output is as follows:
class Hello { public: Hello() { cout << "Hello World!" << endl; } }; Hello obj; int main() {}
Example
#include <iostream> using namespace std; class Hello { public: Hello() { cout << "Hello World!" << endl; } }; Hello obj; int main() {}
Following is the output to the above program:
Hello World!
Using a Class Object
A class object is an instance of a class that is created to use its properties and functions. So, if you add a print statement inside the constructor, it will execute when the object is instantiated without calling a main() function.
Syntax
Following is the output is as follows:
class Hello { public: Hello(); }; Hello::Hello() { std::cout << "Hello World!" << std::endl; } Hello h; int main() {}
Example
#include <iostream> using namespace std; class Hello { public: Hello(); }; Hello::Hello() { cout << "Hello World!" << endl; } Hello h; int main() {}
Following is the output to the above program:
Hello World!
Using Macros and Preprocessor
Using the preprocessor and macros, you can print "Hello World" with an empty main() function. To achieve this, we need to define a macro with #define that executes a print() statement before the main() function. The compiler then replaces the macro definition with actual code before compilation, allowing the output to be printed even though main() is blank.
Syntax
Following is the output is as follows:
#define H cout << "Hello World!" << endl; class A { public: A() { H } }; A a; int main() {}
Example
#include <iostream> #define H cout << "Hello World!" << endl; using namespace std; class A { public: A() { H } }; A a; int main() {}
Following is the output to the above program:
Hello World!