简体   繁体   中英

Calling functions outside functions

I have this code:

std::string* f()
{
  cout << "1";
  return new string("5");
}
std::string a = *f();
std::string b = a.append("2");

int main()
{
  cout << b;
  return 0;
}

This code runs and return 152

How is possible? If compiler is calculating value of its return string at compile time then how come I see 1 when running the code? And if this is done at run time, then I am never calling f() at run time, so I shouldn't see the 1 in the output.

You said:

If compiler is calculating value of its return string at compile time

That is not correct. A compiler can calculate some expressions at compile time but not all expressions. In this case, it can only be computed at run time.

cout << "1";

is executed when you call f() to initialize a with the line

std::string a = *f();

This happens at run time. not at compile time.

b is initialized using the value of a with the line

std::string b = a.append("2");

This also happens at run time, not at compile time.

Your example code prints "1" when global variable a is initialzed with "5", and then after global variable b is initialized with "52", that is when main() runs. So the complete output is "1" followed by "52".

Note that function f() is indeed called, not from main() but by the initializer for global variable a.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM