C If Statement Question
Thanks for the replies! Just one more question, not too sure I understand correctly, but how come you created the Grade enum but don't use it in the code and also how come you had it returns an int instead of enum in the compute_grade function? Much appreciated!
It is generally a good idea to keep input, output and computation separate. In that spirit, it would be good to have something like this function:
enum Grade { Grade_F, Grade_D, Grade_C, Grade_B, Grade_A, }; enum Grade compute_grade(int score) { static int const grade_cuts[4] = {60, 70, 80, 90}; int grade; for (grade = 0; grade < 4; ++grade) if (score < grade_cuts[grade]) break; return grade; }
Never mind my last questions, I played around with the code you gave me and got whats going on, thanks!
Thanks for the replies! Just one more question, not too sure I understand correctly, but how come you created the Grade enum but don't use it in the code and also how come you had it returns an int instead of enum in the compute_grade function? Much appreciated!
It is generally a good idea to keep input, output and computation separate. In that spirit, it would be good to have something like this function:
enum Grade { Grade_F, Grade_D, Grade_C, Grade_B, Grade_A, }; enum Grade compute_grade(int score) { static int const grade_cuts[4] = {60, 70, 80, 90}; int grade; for (grade = 0; grade < 4; ++grade) if (score < grade_cuts[grade]) break; return grade; }
4 looks like a bit of a magic number though, Al, I am disappoint.
Well, I could have left the size of the array implicit in the initialization, and then used sizeof(grade_cuts)/sizeof(*grade_cuts) to recover the 4 in the loop, but I think that would have detracted from the code's clarity, which would be especially bad "For Beginners". In C++ (especially C++11) there are better solutions, but this is a C thread.
EDIT: Here's a version with no magic numbers, and with the grade cuts defined in one place and one place only. If you want to understand how it works, ask Shiftie.
#include <stddef.h>
#define ARRAY_LENGTH(X) (sizeof(X) / sizeof(*X))
#define GRADES_AND_CUTS \
G_A_C(F, 0) \
G_A_C(D, 60) \
G_A_C(C, 70) \
G_A_C(B, 80) \
G_A_C(A, 90)
#define G_A_C(X,Y) Grade_##X ,
enum Grade { GRADES_AND_CUTS };
#undef G_A_C
enum Grade compute_grade(int score) {
#define G_A_C(X,Y) Y ,
static int const grade_cuts[] = {GRADES_AND_CUTS};
#undef G_A_C
unsigned grade;
for (grade = 1; grade < ARRAY_LENGTH(grade_cuts); ++grade)
if (score < grade_cuts[grade])
break;
return grade - 1;
}
char const *grade_name(enum Grade grade) {
#define G_A_C(X,Y) #X ,
static char const *grade_name_table[] = {GRADES_AND_CUTS};
#undef G_A_C
return grade_name_table[grade];
}