Given the task of printing to the terminal, which code block is "best practice"?
string name = get_string("Whats your name? ");
printf("Hello, %s\n", name);
or
printf("Hello, %s\n", get_string("Whats your name? "));
This question has come up two times for me in interviews and seemed to be a sticking point of some kind.
Both times the ladder was held up as the "proper" way but no real explanation why besides taking up less space. Is it due to not taking up a namespace and/or passing functions being more efficient?
Stylistically the first is somewhat better readable, but the second evades a variable which might or might not be used later. Of course one needs to include string. Also note that the second version places the input prompt after the output, not the sequential order.
Generated code: a string object is held in the first version till the end of its scope. In the second a
const char*is expected of theget_stringresult which might be optimized immediately without data flow analysis; inlining without string object.Nevertheless my answer is: