#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()
.
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.
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.
Every C program has a primary function that must be named main . The main function serves as the starting point for program execution.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With