reset password
Author Message
G190852562
Posts: 162
Posted 13:59 Jan 10, 2015 |

What is the advantage of creating constants in enum as opposed to creating each variable individually with the same value?

Also, what is meant by using enum as a label?

kscasado
Posts: 19
Posted 14:12 Jan 10, 2015 |

Much easier way to organize constant values that you will be consistently referring to. Increases readability to call a variable name that can describe something as opposed to just some random value. Look through his lecture slides, he went over this. With a lot of detail 

kknaur
Posts: 540
Posted 16:30 Jan 10, 2015 |

Yes what the person above me said is correct.  If you have a set of related named constants it makes your code a lot more readable to define them all in the same place and in the same way using an enum. 

For the following example I will used the days of the week as constants. You could just internally represent each day with integer values from 0 ~ 6.  I might make a switch statement like this

int day = some day value;

switch (day) {
case 0: do something for monday; break;
case 1: do something for tuesday; break;
...
case 6: do something for sunday: break;
}

This is ok... but I could have used named constants to make the code a bit more readable

Option 1: normal constants

const int MONDAY = 0;
const int TUESDAY = 1;
...
const int SUNDAY = 6;

Option 2: Using an enum

enum Days {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}

Now with either option my switch statement becomes


switch (day) {
case MONDAY: do something for monday; break;
case TUESDAY: do something for tuesday; break;
...
case SUNDAY: do something for sunday: break;
}

And this is what I mean by using them as a "label".  You associate a valid identifier with a constant value in your program to make the code more readable.

Hope this helped!

Last edited by kknaur at 16:31 Jan 10, 2015.
G190852562
Posts: 162
Posted 17:42 Jan 10, 2015 |

So each constant inside that list of enum is considered an enum type?

Also, if I decide to use enum, would the controlling expression be switch(Days) instead of switch(day)? 

kknaur
Posts: 540
Posted 18:01 Jan 10, 2015 |

Yes they are of the enum type, and no you wouldn't use Days for the switch.  Here is an example try it yourself.

#include <iostream>

int main() {
    int choice;

    enum Days {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};

    std::cout << "Choose a day of the week 0 - 1: ";
    std::cin >> choice;

    switch(choice) {
    case MONDAY:
        std::cout << "You chose Monday" << std::endl;
        break;
    case TUESDAY:
        std::cout << "You chose Tuesday" << std::endl;
        break;
    }
    return 0;
}
G190852562
Posts: 162
Posted 19:53 Jan 10, 2015 |

Understood, thanks!