dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Thread: 2 quick questions - (1) enums and (2) switch

  1. #1
    Join Date
    Sep 2015
    Posts
    3

    2 quick questions - (1) enums and (2) switch

    Hey guys, I'm new to these forums and I didn't see any dedicated "beginners" forum. So I'm asking here.

    1. Are enums literally nothing more than an array of const unsigned ints that are presented as names rather than values, because names are more useful for humans than values in the given situation?

    enum foo = { LOW, MEDIUM, HIGH };
    vs.
    int foo [] = { 3, 6, 8 };

    2. Are switch statement nothing more than a cleaner way to handle larger groups of if statement. If so, what are the benefits of using if statements at all?

    Thanks in advance.

  2. #2
    Join Date
    Sep 2015
    Posts
    3

    Re: 2 quick questions - (1) enums and (2) switch

    I should mention that I'm currently going through "Beginning C++ Through Game Programming" by Michael Dawson. And My questions are a result of me wanting to know the more obscure parts of C++ and that I've had a really hard time finding a clear explanation of these things that aren't either ambiguous, subjective or both.

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,555

    Re: 2 quick questions - (1) enums and (2) switch

    1. No. An enum is not an array. It's a way of assigning a name to a value in a series of integer constants.

    2. Pretty much. A switch statement only works on expressions that evaluate to an integral type. if statements work on any expression. You can't say
    switch (a == b) for example.

  4. #4
    Join Date
    Oct 2008
    Posts
    1,456

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by Madolite View Post
    Are switch statement nothing more than a cleaner way to handle larger groups of if statement. If so, what are the benefits of using if statements at all?[...] I've had a really hard time finding a clear explanation of these things that aren't either ambiguous, subjective or both.
    the first thing you should understand as a beginner is that programming languages are primarily made for people to read and manipulate, rather than for computers to run. Otherwise, we'd all write in byte code ain't we ?

    so, when you compare language constructs like "if" and "switch" you should firstly ask yourself what they mean, rather than what they do (*). Yes, it's subjective ( all human affairs are ) and it's on purpose, but it doesn't mean it's "obscure". Of course, how those constructs are actually processed by a compiler and then a computer is important, but somewhat secondary as far as the choices behind the language syntax are concerned.

    (*) you've probably already heard of the notion of Turing completeness; well, simplifying, it means that all computers that can count and access some linear memory are essentially the same as far as what they can/cannot do; so, it's not surprising that programming languages are fillled of tons of equivent ways of <doing> the same thing ...

  5. #5
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,602

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by Madolite View Post
    Hey guys, I'm new to these forums and I didn't see any dedicated "beginners" forum. So I'm asking here.

    1. Are enums literally nothing more than an array of const unsigned ints that are presented as names rather than values, because names are more useful for humans than values in the given situation?
    enum foo = { LOW, MEDIUM, HIGH };
    vs.
    int foo [] = { 3, 6, 8 };
    Enumeration, indeed, is a type that transparently casts to integer type. But by no means it's an array of anything. Array possess a memory region at runtime, while enumeration is a compile time information. It's a way of introducing a bunch of associated definition statements specifically for kinda integer type constants.

    Quote Originally Posted by Madolite View Post
    2. Are switch statement nothing more than a cleaner way to handle larger groups of if statement. If so, what are the benefits of using if statements at all?
    if() operates on conditions (boolean) while switch() operates on integer data. It's totally up to you, what operator better suits your needs in a particular situation.

    Code:
    int input = 0;
    . . .
    if (input == 0) {
        // handle 0 case
    } else if (input == 1 || input == 2) {
        // handle 1 or 2 case
    } else if (input == 15) {
        // handle 15 case
    } else {
        // handle other cases by default
    }
    is logically equivalent to
    Code:
    int input = 0;
    . . .
    switch (input) {
    case 0: { /* handle 0 case*/ } break;
    case 1:
    case 2: { /* handle 1 or 2 case */ } break;
    case 15: { /* handle 15 case */ } break;
    default: { /* handle other cases by default */ }
    }
    Best regards,
    Igor

  6. #6
    Join Date
    Sep 2015
    Posts
    3

    Re: 2 quick questions - (1) enums and (2) switch

    Awesome. Thanks for the replies.

    Quote Originally Posted by superbonzo View Post
    ...programming languages are primarily made for people to read and manipulate, rather than for computers to run.
    But not exclusively, which is why I don't assume anything and instead ask questions to clear things up.
    Last edited by Madolite; September 23rd, 2015 at 05:05 AM.

  7. #7
    Join Date
    Jun 2015
    Posts
    208

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by Madolite View Post
    1. Are enums literally nothing more than an array of const unsigned ints that are presented as names rather than values, because names are more useful for humans than values in the given situation?
    That's roughly correct but an even closer analogy would be to view an enum like a struct holding constants like this,

    Code:
    struct foo {
        static const int LOW = 3;
        static const int MEDIUM = 6;
        static const int HIGH = 8;
        int val; // holds one of the constants
    };
    Also note that since C++ 11 (the new major version) there's a new form of enum called strongly typed enum. In most situations it's a good idea to prefer the new enum.

    2. Are switch statement nothing more than a cleaner way to handle larger groups of if statement. If so, what are the benefits of using if statements at all?
    One usually considers a switch statement when the corresponding if-else chain becomes long and winding and hard on the eye.

    But there's also a performance argument. In an if-else chain the selections are evaluated one by one from the beginning to the end whereas in a switch statement the evaluation order is not specified and this opens up for compiler optimizations. When there are many selections with equal probability (of being true) then the switch is faster than a corresponding if-else. If on the other hand some selections have a very high probability and these are put at the beginning of an if-else then this is faster than a switch.
    Last edited by tiliavirga; September 24th, 2015 at 02:08 AM.

  8. #8
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by tiliavirga View Post
    That's roughly correct but an even closer analogy would be to view an enum like a struct holding constants like this,
    what ?
    No. that's not even remotely what an enum is in either a practical or a semantical point of view.

  9. #9
    Join Date
    Jun 2015
    Posts
    208

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by OReubens View Post
    what ?
    No. that's not even remotely what an enum is in either a practical or a semantical point of view.
    According to the C++ standard it's spot on:

    "An enum is a distinct type with named constants"

    I just forgot to put in the variable to hold the constants. What I suggest is now the very (and bare) essense of an enum.
    Last edited by tiliavirga; September 23rd, 2015 at 07:35 AM.

  10. #10
    Join Date
    Oct 2008
    Posts
    1,456

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by tiliavirga View Post
    an even closer analogy would be to view an enum like a struct holding constants like this
    you're also missing a "static" before those const's ... and I'd also add a conversion operator to the underlying type and remove any reference to 'int', because the actual underlying integer type is choosen by the compiler based off the given enumerators ...

    even then, constants can form lvalues, enumerators can't, so it's not the kind of "constants" the standard's referring to...

    Quote Originally Posted by tiliavirga View Post
    In an if-else chain the selections are evaluated one by one from the beginning to the end whereas in a switch statement the evaluation order is not specified and this opens up for compiler optimizations
    uhm, evaluation order is fully specified in a switch: the (only) argument is evaluated once and case labels are not "evaluated", they're jumped through in order of appereance.
    The performance bonus is rather due to the fact that switch operates on strictly integer types and matches against compile time integral constants, possibly enabling faster lookup table implementations, rather than the linear if() branches. Even than, I suppose nothing forbids a compiler to optimize a switch-looking if() accordingly ...

  11. #11
    Join Date
    Jun 2015
    Posts
    208

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by superbonzo View Post
    you're also missing a "static" before those const's ... and I'd also add a conversion operator to the underlying type and remove any reference to 'int', because the actual underlying integer type is choosen by the compiler based off the given enumerators ...
    It was just an example of a bare minimum enum implementation to help a newbie OP get the concept. It's fully functional as it stands now and will work fine as a rudimentary enum. Beyond that its better to use the real thing.

    even then, constants can form lvalues, enumerators can't, so it's not the kind of "constants" the standard's referring to...
    The term "named constant" occurs twice only in the standard and both times in association with enums.

    - " ... enumeration, which comprice a set of named constant values" (3.9.2), and
    - "An enumeration is a distinct type with named constants." (7.2)

    In my view these are general descriptions of what constitutes an enum in principle and "named constant" simply denotes a symbol that doesn't change value, nothing else.

    uhm, evaluation order is fully specified in a switch: the (only) argument is evaluated once and case labels are not "evaluated", they're jumped through in order of appereance.
    The performance bonus is rather due to the fact that switch operates on strictly integer types and matches against compile time integral constants, possibly enabling faster lookup table implementations, rather than the linear if() branches. Even than, I suppose nothing forbids a compiler to optimize a switch-looking if() accordingly ...
    No, the performance bonus is due to the fact that the order by which the switch condition is compared with the case labels is not specified. It has nothing to do with the fact that case labels are integral. Switch optimization is used also in languages where they may not be (like say in Java where case labels can be strings as well).

    The most common optimization is to arrange case labels in sorted order and search binary style for a matching case label. The resulting performance is O(log N). Case labels can also be held in a table which is searched using hashing or indirect jumping. In that case the switch becomes an O(1) operation.

    No, a compiler couldn't execute an if-else chain as if it were a switch even when such a transformation is possible. It's because the if-else execution order is defined. If the first if condition yields false the else substatement is executed leading up to the second if statement of the chain, etcetera.

    So when a switch is executed (or evaluated as I usually say) all case labels are considered in one go (conceptually in parallel) whereas an if-else chain is executed one if at a time in strict sequential order.
    Last edited by tiliavirga; September 24th, 2015 at 02:36 AM.

  12. #12
    Join Date
    Oct 2008
    Posts
    1,456

    Re: 2 quick questions - (1) enums and (2) switch

    "functional" ? by storing a copy of all constants in all and every instance ... ?

    regarding the switch thing, well if you play with terminology ( FYI, evaluation has a definite meaning in c++ ) I suppose you can prove anything, so I won't insist my dear ...

    EDIT: ooh just see you edited your post ...
    Last edited by superbonzo; September 24th, 2015 at 02:56 AM.

  13. #13
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: 2 quick questions - (1) enums and (2) switch

    Quote Originally Posted by tiliavirga View Post
    No, the performance bonus is due to the fact that the order by which the switch condition is compared with the case labels is not specified. It has nothing to do with the fact that case labels are integral. Switch optimization is used also in languages where they may not be (like say in Java where case labels can be strings as well).
    On most modern compilers the switch won't have any sort of speed benefit over a chain of if/else if/else if... Because optimizers have gotten "smart enough" to detect the situation and end up treating both identically.

    The most common optimization is to arrange case labels in sorted order and search binary style for a matching case label. The resulting performance is O(log N). Case labels can also be held in a table which is searched using hashing or indirect jumping. In that case the switch becomes an O(1) operation.
    For a compiled language like C++ where theres only integral switching, switches will tend to be optimized either as
    * a series of test+conditional jump instructions (for 'low' number of case values and values being spread out)
    * as a jumptable (for consecutive/nearby values) of addresses
    * as a table of indexes into a jumptable of addresses (for many switch values where many values map to a single execution branch)
    * i've also seen 2 or 3 stage state machines.
    * hybrid cases combining one or more of the above when you have several far away groups of bunched up values.


    I can not recall a single case where the switch (or series of if/else if) was compiled into an actual binary search or a hashtable. Although debatably, the above mentioned test/conditional jump sequences will tend to optimize into a series of tests that give the effect of a binary search approach, but I've never actually seen a compiler generate a table it searches through.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)