Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you print anything in C++, before entering into the main function?

Tags:

c++

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.

like image 558
user1231897 Avatar asked Feb 25 '12 00:02

user1231897


People also ask

What happens before main function in C?

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.

How do you invoke a function before main in C?

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().

Can you print a function in C?

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?

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.


2 Answers

#include <iostream>

std::ostream & o = (std::cout << "Hello\n");

int main()
{
   o << "Now main() runs.\n";
}
like image 101
Kerrek SB Avatar answered Oct 03 '22 21:10

Kerrek SB


#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

like image 44
Armen Tsirunyan Avatar answered Oct 03 '22 21:10

Armen Tsirunyan