-
Advantages in struct?
This was an exercise comparing to methods of holding month/days of month data and displaying them. Which would you use and why?
The exercise is from C++ Programming Language 3rd edition 5.9 #7, pg 105.
Code:
// year.cc - to compare an array of structs to an array of cstrings
// holding month/day of month data
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
const char *months[12] = {"January","February","March","April",
"May","June","July","August",
"September","October","November","December"};
int daysofmonths[12]={31,28,31,30,31,30,31,30,30,31,30,31};
struct monthdays{
char month[10];
int days;
};
monthdays year[12]={"January",31,"February",28,"March",31,"April",30,
"May",31,"June",30,"July",31,"August",30,
"September",30,"October",31,"November",30,"December",31};
for (int index=0; index < 12; ++index)
{
cout << months[index] << "\t\t\t" << daysofmonths[index] << endl;
}
for (int index=0; index < 12; ++index)
{
cout << year[index].month << "\t\t\t" << year[index].days << endl;
}
return 0;
}
forgot to declare everything as const oh well
-
At this point in your learning, don't worry about it. The exercise(and chapter?) are introducing you to the mechanics of how structs work. The next step is learning about classes(which except for one minor detail are identical to structs) and their use in object oriented programming, where you will soon discover their unique properties.
-
Yes, I see no advantage in the struct in the given example. It doesn't even encapsulate the data because default access is public.
The code is no easier to read and the exercise specified char array as apposed to the string class.
Perhaps it is just a mechanical exercise, though I felt he wanted some type of comparison. He doesn't explicitly ask this though.
-
Try calling a function or two
Compare
do_something ( month, days )
with
do_something ( monthdays )
Now imagine you had 20 related items
The first call would have 20 params all of a sudden, yet the 2nd one would remain at 1 parameter
-
Good point!
In such a case a struct would be neater even in the simple example you illustrated the structure is eazier.
-
The time_t has never been beat, I say go with that. You can even derive a new structure from the tm time struct [time.h, ctime].