Both these calls to get_string and get_string2 return objects which go out of scope when the function returns. Shouldn't the returned object be an address in memory which goes out of scope after the function returns? This is using Visual Studio 2008. Should this always work? Why?
#include <iostream>
enum myID { SMALL, MEDIUM, LARGE };
const char* get_string(myID id) {
switch(id){
case SMALL: return "small";
case MEDIUM: return "medium";
case LARGE: return "large";
default: return "unknown";
}
}
const char* get_string2(myID id) {
char* s = 0;
switch(id){
case SMALL: s = "small"; return s;
case MEDIUM: s = "medium"; return s;
case LARGE: s = "large"; return s;
default: return "unknown";
}
}
int main() {
std::cout << get_string(SMALL) << std::endl;
std::cout << get_string2(SMALL) << std::endl;
return 0;
}