Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing C++ output without changing the main() function [closed]

Tags:

c++

#include<iostream.h>
void main()
{
    cout<<"Love";
}

The question is how can we change the output of this program into "I Love You" without making any change in main().

like image 775
Binu Avatar asked Mar 14 '09 16:03

Binu


People also ask

Is main () function mandatory in C?

So actually C program can never run without a main() . We are just disguising the main() with the preprocessor, but actually there exists a hidden main function in the program.

Can a program be compiled without main () function in C?

The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution.

Is it necessary to start the execution of a program from the main () in C?

Every C program has a primary function that must be named main . The main function serves as the starting point for program execution.

What is main () in C?

The main function in C programming is a special type of function that serves as the entry point of the program where the execution begins. By default, the return type of the main function is int. There can be two types of main() functions: with and without parameters.


1 Answers

Ok, fixing your main function and iostream.h ... This is the way

#include <iostream>

// to make sure std::cout is constructed when we use it
// before main was called - thxx to @chappar
std::ios_base::Init stream_initializer;

struct caller {
    caller() { std::cout << "I "; }
    ~caller() { std::cout << " You"; }
} c;

// ohh well, for the br0ken main function
using std::cout;

int main()
{
    cout<<"Love";
}

I figured i should explain why that works. The code defines a structure that has a constructor and a destructor. The constructor is run when you create an object of the struct and the destructor is run when that object is destroyed. Now, at the end of a struct definition, you can put declarators that will have the type caller.

So, what we did above is creating an object called c which is constructed (and the constructor called) at program start - even before main is run. And when the program terminates, the object is destroyed and the destructor is run. In between, main printed "Love".

That pattern actually is very well known by the term RAII which usually claims some resource in the constructor and releases it again in the destructor call.

like image 88
Johannes Schaub - litb Avatar answered Jan 01 '23 19:01

Johannes Schaub - litb