using switch statements

This question is somewhat related to my previous question. Instead of a myriad if (strcmp...) else statements, wouldn't it be more efficient to use something like this :


switch (VariableNameString)

case "MyVariable" : MyVariable++;


If I have completely misunderstood the way switch works please tell me. Also if this is more cumbersome in processing please tell me as well. Thanks in advance again.


Comments

  • : This question is somewhat related to my previous question. Instead of a myriad if (strcmp...) else statements, wouldn't it be more efficient to use something like this :


    : switch (VariableNameString)

    : case "MyVariable" : MyVariable++;


    : If I have completely misunderstood the way switch works please tell me. Also if this is more cumbersome in processing please tell me as well. Thanks in advance again.


    You have not misunderstood switch/case, but there are two problems:

    First, switch/case statements can only evaluate integer type values.

    Second, strings have no natural == operator, so even if it could be used, there would be no way to compare them.


    It would theoretically be possible to create a string class that returns ints when asked for one (like taking each char value and stringing them together)

    but that wouldn't work for long strings (like, 4 chars). OK, that was rambling.


    That's why it wouldn't work.








  • : First, switch/case statements can only evaluate integer type values.


    This is true. You're unfortunately relegated to using if-else if-else if-else chains or using tables of strings when trying to decide about which string matches. The table idea has its merits as it makes the comparison mechanism a little less ugly to look at.



    : Second, strings have no natural == operator, so even if it could be used, there would be no way to compare them.


    Also true. Strings in C aren't really strings. They're character arrays. What I mean by this is that, like any other array, they cannot be directly assigned, compared, or passed to and from functions as entire 'things'.


    You'll have to use if statements and the strcmp function, or create a table of strings and numbers and then a routine to do a table lookup (the latter is my favourite, personally).





  • Thanks everyone. I tried the chains of if-else, and found myself with some code that was quite hard to read. I decided to use a look up table of sorts and it has resulted in much cleaner code. Thanks again for your help.




Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories