2

Hello I've been asked to write a C++ program with an empty main function body but the program should print: "hi there!".

So I've done it this way:

#include <iostream>


struct Foo
{
    Foo(){std::cout << "hi there!\n";}
}fobj;

int bar()
{
    std::cout << "hi there!\n";
    return 0; // arbitrary value
}

int x{bar()};
double pi = (std::cout << "hi there!\n", 3.14);



int main()
{

}

The output:

hi there!
hi there!
hi there!

It looks it works fine from my codeblocks but on my phone using "Coding C++" it says: process terminated. signal 11.

  • So is all my case are well-defined or there's something disastrous? Thank you.
Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • Does your phone environment do the right thing for `std::cout` used inside of `main()` ? – Ben Voigt Dec 07 '20 at 18:23
  • @BenVoigt: Sure. – Itachi Uchiwa Dec 07 '20 at 18:23
  • 3
    It's probably the **Static Initialization Order Fiasco**; take a look at https://stackoverflow.com/q/36563223/103167 and https://stackoverflow.com/q/8784892/103167 – Ben Voigt Dec 07 '20 at 18:24
  • @BenVoigt: But that problem maybe occur only in header files where an object is initialized from the other. isn't it? – Itachi Uchiwa Dec 07 '20 at 18:25
  • 6
    Here you have a static object `Foo fobj` and another one `std::ostream std::cout`, which is initialized first? – Ben Voigt Dec 07 '20 at 18:27
  • 6
    In C++11, `std::cout` (and other standard streams) is guaranteed to be initialised before other objects of static storage duration. Before that, `std::cout` is only guaranteed to be initialised at the start of `main()`, and the order of initialisation of `std::cout` relative to other objects of static storage duration is unspecified. – Peter Dec 07 '20 at 18:38
  • See [this question](https://stackoverflow.com/questions/8784892/is-stdcout-guaranteed-to-be-initialized) for the details about @Peter's comment. – 1201ProgramAlarm Dec 07 '20 at 18:45
  • 1
    @Peter Looks like an _answer_. – Asteroids With Wings Dec 07 '20 at 19:16
  • There's a pre-C++11 workaround: [`std::ios_base::Init`](https://stackoverflow.com/a/8785008/15416) – MSalters Dec 08 '20 at 00:27

0 Answers0