So in my classes I've taken I was told by the teacher "case statements and if-else statements are the same things essentionally" so why learn both? and so I was not taught about cases.
Besides the fact I should learn it anyway incase I need it for someone elses code, should I learn these for an actual purpose? Are they good for something that if-else isnt as good for?

Recommended Answers

All 3 Replies

basically if you have series of conditions that rely on different values of the same variable then a case construct is simnpler to code than a series of if-else statements.

if else is much more flexible than cases. But there are times, when cases can be much simpler. Example, a menu system. At school, for any such menus we use cases.

Idea is, if the the condition is not complex and just depends on the value of a single variable, switch cases are better.......

Besides the inherent simplicity of the switch-case compared to else-if, there is also some performance benefit to a switch-case, at least, nominally (i.e., if the compiler is not smart enough to produce the most efficient code in either case). In the classic use of a switch-case, something like this:

enum MyEnum {
  Zero,
  One,
  Two,
  Three
};

void printCast(MyEnum value) {
  switch(value) {
    case Zero:
      std::cout << "Zero" << std::endl;
      break;
    case One:
      std::cout << "One" << std::endl;
      break;
    case Two:
      std::cout << "Two" << std::endl;
      break;
    case Three:
      std::cout << "Three" << std::endl;
      break;
  };
};

then, the switch-case is going to be more efficient because an enum is just a type-safe integer value, and the compiler will, by default, assign the values as 0, 1, 2, ... for the different entries in the enum type. When you make a switch statement like above, the code is not going to evaluate the individual conditions (i.e., (value == Zero), (value == One), ...) but will, instead, do a jump in execution based on the value of the switch variable. And that is technically more efficient. Of course, the caveat here is that even with a else-if version, it is possible that the compiler will figure out that it is equivalent to the above switch-case, and produce the same "most efficient" code anyways. But, it is one more thing to consider.

The basic lesson here is that if a switch-case statement is the more natural way of expressing something, then use it, but don't go out of your way to use a switch-case (some people tend to be "switch-case fanatics", don't be one of those people).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.