Is it considered efficient to pass functions as arguments over passing variables?

69 views Asked by At

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?

1

There are 1 answers

2
Joop Eggen On

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 the get_string result which might be optimized immediately without data flow analysis; inlining without string object.

Nevertheless my answer is:

  • this seems interactive code, so a possible optimisation is irrelant;
  • even a C reference I saw used the first style - for clarity evidently;
  • only when the code contains many variables or has really many lines, one should use the second style.