return parameter or normal return

In c++ it's valid to do this:

1
2
3
4
5
6
7
8
9
10
11
12
string what_to_do(const string& day){
     if(dayIsWeekend(day)){
        return "drink";
     }else{
        return "work";
     } 
}

int main(){
    todays_plan=what_to_do("Saturday");
    cout << todays_plan\n;
}


or....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void what_to_do(const string& day,string * plan){
     if(dayIsWeekend(day)){
        *plan = "drink";
     }else{
        *plan = "work";
     } 
}

int main(){
    string todays_plan;
    what_to_do("Saturday",&todays_plan);
    cout << todays_plan\n;
}



What are the reasons to do this one way or another. Are there different situations that are similar where one might be prefered over the other. The only good reason I can think of to do it the second way ever is if you need to return two things in the function.

What if the function was simply taking in a string, concatinating two characters to the front of it and returning it. would you write that to work like this:

 
mystring=concatonator(mystring);

Or...
 
concatonator(&mystring);




I'm asking a question as to why you'd want to use string * plan as an argument and not string &plan so that you could just input todays_plan. I haven't compiled this and my mind just went blank a few minutes before I started writing this, yet...

If you want to avoid a long chain of arguments, which sometimes happens with functions that use reference pointers as arguments, then use the first one. If you need to manipulate more than one thing outside of the function, then use global variables. Except that some people think that global variables are evil and in that case you need to pass the variable names as arguments.

-Albatross

EDIT: 300 posts and counting.
Last edited on
Topic archived. No new replies allowed.