Printing without changing main function

watch_video

The below C++ code will print "Hello World".

#include 
int main()
{
    cout<<"Hello World";
}
Without modifying main function, add code to print "Ritambhara" before "Hello World". You cannot add/remove any statement to main function

Solution:


This is a trick question. We cannot change main and main is the first function that gets called.

So in a way we have to print "Ritambhara" even before the first function is called.Let us see what happens before calling main:

  1. Program is loaded into memory.
  2. Static and global variables (also called load-time variables) are allocated memory and are initialized.

we cannot do anything in point 1. But we can print as a side effect of a global variable being initialized. Below is the code

#include 
class Temp{
public:
    // Constructor
    Temp(){
        cout<<"Ritambhara;
    }
}
Temp obj;
int main()
{
    cout<<"Hello World";
}

Global variable obj will be allocated memory and gets created before main function is called. When obj will be created, the constructor of Temp class will be called and it will print Ritambhara.

Output of this code will be

Ritambhara
Hello World
Personally, I does not ask such kind of questions in the interview. Because such questions rely more on tricks than on algorithms. But I have seen many interviewers asking such questions. Esp. in the companies where C++ is more important that algorithms.

Tags:

CPP Trick Code

0 Comments

Leave a comment