Hi,
I have been reading through my c++ book and came across an example I do not fully understand, with very little explanation given. I am hoping someone from these forums can better explain what is going on here.
Code:
#include <iostream>
using namespace std;
struct travel_time
{
int hours;
int mins;
};
const int Mins_per_hour = 60;
travel_time sum(travel_time t1, travel_time t2);
void show_time(travel_time t);
int main()
{
travel_time day1 = { 5, 45 }; // 5hrs 45 min
travel_time day2 = { 4, 55 }; // 4hrs 55 min
travel_time trip = sum(day1, day2);
cout << "Two-day total: ";
show_time(trip);
travel_time day3 = { 4, 32 };
cout << "Three-day total: ";
show_time(sum(trip, day3));
cin.get();
cin.get();
return 0;
}
travel_time sum(travel_time t1, travel_time t2)
{
travel_time total;
total.mins = (t1.mins + t2.mins) % Mins_per_hour;
total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / Mins_per_hour;
return total;
}
void show_time(travel_time t)
{
cout << t.hours << " hours, "
<< t.mins << " minutes\n";
}
On line 13 there is a function header named sum, yet on line 19-20 they are accessing that function with different variable names. (I dont get why I just assumed they where objects being created, so I can let that pass).
However on line 22 (day1 and day2) data is passed to the sum function while being stored in the variable trip, so it can be accessed from main. How exactly this happening?
day 1 has two paramaters, day 2 also has two paramets
so how does it fit inside the sum function? The only way I see is by adding them together....
so day1 = 50
day 2 = 59
so the following code:
travel_time trip = sum(day1, day2);
would look like:
travel_time trip = sum(50, 59);
But then going to line 41 makes no sense
total.mins = (t1.mins + t2.mins) % Mins_per_hour;
total.mins = 50 + 59 % 60 which is 49 which the compiler does not output.