Please explain the output of below program

106 Views Asked by At

Just run this program and explain me output of last line why it prints "g" instead of "f". Here my intention is to know why it is showing previous functions return value?

#include <iostream>
#include <string>

std::string f() {
  return "f";
}

std::string g() {
  return "g";
}

int main() {
  const char * s = f().c_str();
  std::cout << "s = " << s << std::endl;
  std::cout << "g() = " << g() << std::endl;
  std::cout << "s = " << s << std::endl;
}
1

There are 1 best solutions below

0
On

That is because you are relying on a temporary value generated by "f().c_str()".The value set is not extended in the future calls to your char array i.e. s rather contains garbage since it has become dangling. Moreover it doesnt necessarily print 'g' always.