Can you print anything in C++, before entering into the main function?
It is interview question in Bloomberg:
Answer :create a global variable assigning value from printf statement with some content.
For most C and C++ programs, the true entry point is not main , it's the _start function. This function initializes the program runtime and invokes the program's main function. The use of _start is merely a general convention. The entry function can vary depending on the system, compiler, and standard libraries.
Functions that are executed before and after main() in C To do this task we have to put attribute for these two functions. When the attribute is constructor attribute, then it will be executed before main(), and when the attribute is destructor type, then it will be executed after main().
Print Function in C, C++, and PythonPrint function is used to display content on the screen. Approach: Some characters are stored in integer value inside printf function. Printing the value as well as the count of the characters.
Can the main() function left empty? Yes, possibly the program doing nothing. Can one function call another? Yes, any user defined function can call any function.
#include <iostream>
std::ostream & o = (std::cout << "Hello\n");
int main()
{
o << "Now main() runs.\n";
}
#include <iostream>
struct X
{
X()
{
std::cout << "Hello before ";
}
} x;
int main()
{
std::cout << "main()";
}
This well-formed C++ program prints
Hello before main()
You see, the C++ standard guarantees that the constructors of namespace-scope variables (in this example, it's x
) will be executed before main()
. Therefore, if you print something in a constructor of such an object, it will be printed before main()
. QED
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