0

I am pretty new with coding and compiling small programs in C and I have looked at the multiple threads regarding this issue and yet still haven't found or understood the answer I am looking for. I guess could someone explain in terms a kindergartener would understand, Why an if statement would be better than a switch or vise versa?

The reason I'm asking is because I find it easier mentally, to accomplish the task in a switch vs an if.

Should I practice more if's?

Without getting me lost in complex issues, will there be scenarios where switch cases will not work later on in complex programming?

The example I have is I choose to make a Celsius to Fahrenheit conversion with a switch instead of an if. Was this a "poor choice"?

Any feed back would be greatly appreciated especially if I can grasp the answer given.

Here's my code

{
int cel, fah;
char answer = 0;

printf("What would you like to convert from? Type: 'C' Celsius / 'F' for Fahrenheit\t");
scanf(" %c", &answer);

switch(answer){

    case 'C':
    case 'c':
        printf("Enter Temperatur in Celsius:\t");        
        scanf("%d", &cel);

        fah = (cel * 1.8) + 32;

        printf("The Temperature in Fahrenheit is: %d\t\n", fah);
    break;

    case 'f':
    case 'F':
        printf("Enter Temperature in Fahrenheit:\t");
        scanf("%d", &fah);

        cel = (fah - 32) / 1.8;

        printf("The Temperature in Celsius is: %d\t\n", cel);
    break;

    default:
        printf("ERROR!!!\n");
}

return 0;
Barmar
  • 741,623
  • 53
  • 500
  • 612
Newbee2C
  • 19
  • 4
  • 1
    I don't know how a `switch` statement would be useful for a Celsius to Fahrenheit converter. Can you update the question to show some code? – Keith Thompson Oct 27 '16 at 22:14
  • 5
    "Should I practice more if's?" - You should pactice more C. – too honest for this site Oct 27 '16 at 22:15
  • Does this help? http://stackoverflow.com/questions/449273/why-the-switch-statement-and-not-if-else – busuu Oct 27 '16 at 22:15
  • 1
    `F = C * 9 / 5 + 32` - what is it about this which requires an `if` or `case`? – Bob Jarvis - Слава Україні Oct 27 '16 at 22:16
  • 1
    "The reason I'm asking is because I find it easier mentally, to accomplish the task in a switch vs an if." As @Olaf wrote. Write your code a couple of times from scratch in both versions - one with `if`s and one with `switch` until you are familiar with both. Especially train the things you find difficult - *repetitio est mater studiorum*, as they say. – Paweł Pela Oct 27 '16 at 22:19
  • Using a `switch` statement everywhere in place of `if` is a very bad idea IMHO. Not because it won't work functionally but because real code is inevitably consumed by many more people than just the original author. And nobody will thank you for changing common conventions. – kaylum Oct 27 '16 at 22:22
  • I did Keith Thompson. Kaylum, your speaking more towards people using and updating future code I might write? – Newbee2C Oct 27 '16 at 22:36
  • "Why an if statement would be better than a switch or vise versa?" Which is "better" is a primarily opinion-based question, which is off-topic for SO. – Keith M Oct 27 '16 at 22:39
  • Cases like the one in the code you show are a good fit for `switch` because you're checking for any of several integer values to select one of several code paths. In many other situations a `switch` doesn't substitute for an `if` in a straightforward way, and even when it does it may not be simpler. – Dmitri Oct 27 '16 at 22:44
  • 1
    Note that with `switch`, the `case` must be constant and an integer type. `if()` does not have this limitation. Even is one side of the test condition is constant, if there is a reasonable chance the code may evolve to a variable compare, code as `if()` now. If the constant side might become non-integer type, code as `if()`. – chux - Reinstate Monica Oct 27 '16 at 23:32
  • "Better" is vector in a multidimensional space. Unless there are other relevant aspects, concentrate on readability. "I can't wrap my head around it" is a bad guide. As a kid, you most certainly had problems first to "wrap your head around" the concept multiplication. But you certainly accept it's use-cases now. – too honest for this site Oct 28 '16 at 01:57
  • Thank you all for your feed back. This has been very helpful and much appreciated. – Newbee2C Oct 28 '16 at 05:56

4 Answers4

1

Without getting me lost in complex issues, will there be scenarios where switch cases will not work later on in complex programming?

In theory, you can frame any if-else block with either a single switch statement or nested switch statements.

In practice, a switch statement works well with a single integral value.


N.B. What follows is a matter of opinion.

If you have multiple conditional statements, such as:

if ( a > 10  )
{
   ...
}
else if ( b <= 25 )
{
   ...
}
else
{
   ...
}

use of switch statements is not the right approach.

If you are able to branch based on an integral value and there are more than 2 branches, it is better to use a switch statement.

Example 1

if ( a == 10 )
{
    doThis();
}
else
{
   doThat();
}

is better than

switch (a)
{
   case 10:
      doThis();
      break;

   default:
     doThat();
}

Example 2

switch (a)
{
   case 10:
      do10();
      break;

   case 20:
      do20();
      break;

   case 30:
      do30();
      break;

   default:
     doDefault();
}

is better than

if ( a == 10 )
{
    do10();
}
else if ( a == 20 )
{
    do20();
}
else if ( a == 30 )
{
    do30();
}
else
{
   doDefault();
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you, I guess my brain is wrapped around one concept. – Newbee2C Oct 27 '16 at 22:32
  • `switch (1 && 2) { case 0: ... case 1: ... }` or use the `true` and `false` macros. logical/comparison/etc. operators yield an `int` result in C. – too honest for this site Oct 27 '16 at 22:43
  • Removed the DV, I still think the question is too much opinion-based. Most ppl get a feeling about when to use each construct when they practice. Like for most other things. – too honest for this site Oct 28 '16 at 01:51
  • @Olaf, it sure is a matter of opinion. – R Sahu Oct 28 '16 at 01:55
  • If it's opion based then why not have that explained in more detail? The text, lectures, and videos I have seen just say either or or will work and I guess my problem in understanding some of these concepts is their applications and what works best where and when. Isn't it more theory based instead of opinion? – Newbee2C Oct 28 '16 at 06:00
  • @Newbee2C: Because that's a close reason actually. Such questions are off-topic for stack overflow. We are neither a discussion nor a tutoring site. Don't try learning C from obscure youtube videos, but read a good C book (yes, these paper-thingies; some are also available as ebook)! Most of the videos are imprecise - at best - and don't give you the whole picture you need. – too honest for this site Oct 29 '16 at 03:37
0
if (either compare values are not integer types) Use_if();
else if (both compare values are variables or maybe in the future ) Use_if();
else if (code is easier to understand as if) Use_if();
else if (code is easier to understand as switch) Use_switch();
else if (code guidelines suggest prefer if) Use_if();
else if (code guidelines suggest prefer switch) Use_switch();
else if (many constants are used) Use_switch();
else Use_if();
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

To appreciate the difference between the two, consider the following two blocks of JS code that accomplish the same thing. One uses if statement and the other using switch statement. One can argue about the elegance and efficiency of one over the other.

Using if with else-if...

var name = "Wolverine";

if(name=="Spider-Man"){
    console.log("good guy!");
} 
else if(name=="Deadpool"){
    console.log("good guy!");
} 
else if(name=="Loki"){
    console.log("bad guy!");
}
else if(name=="Magneto"){
    console.log("bad guy!");
}
else if(name=="Wolverine"){
    console.log("good guy!");
}
else{
    console.log("hmm…");
}

Using switch...

var name = "Wolverine";
switch(name) {
    case "Spider-Man":
    case "Deadpool":
    case "Wolverine":
        console.log("good guy!");
        break;
    case "Loki":
    case "Magneto":
        console.log("good guy!");
        break;
    default:
        console.log("hmm…");
}
SteveSeow
  • 295
  • 1
  • 3
  • first off, fall-throughs are considered a bad practice, so i wouldn't suggest people use them. second, if you want to make a case for efficiency in this context, if statements are far better than the switch in your example, you've just written the if statements inefficiently `if( goodGuyArray.includes( name ) )` – Dave Maison Apr 18 '22 at 15:19
-1

For your example, Celsius to Farenheit conversion, an 'if' is probably better to use than a switch, although there is nothing wrong with using a switch in terms of performance.

A switch basically just makes it easier to deal with situations in which you may have a wide variety of different choices to make based on the value of a given variable.

Let's say you have a variable which might have values A - Z, and for each possible value, you want to perform a different action. With if statements, you'll end up with a very long chain of conditionals:

if(value == 'A')
{ //do something
}
else if (value =='B'){
//do something else}
....
else{ //default}

A switch just makes this easier to deal with

switch(value){
case 'A':
  //do thing
  break;
case 'B':
  //do other thing
  break;
default:
  //default
  break;
}

For a variable with many possible values, the switch saves you time and effort, and is more readable.

For something with only two possible values though, like celsius and farenhiet, the switch isnt actually more readable or compact.

if(celsius)
{
//do thing
}else{
//do other thing
}

Is probably more readable than

switch(temperature){
case celsius:
 //do thing
 break;
case farenheit:
 //do thing
 break;
}

And faster/easier to code.

Logically, they are the same, but which one you use is really a matter of readability, effort, and time.

PLan
  • 133
  • 7
  • I'm not sure why this was downvoted. Care to explain what I got wrong? – PLan Oct 27 '16 at 22:26
  • Thank you, yours and R Sahu, helped me, I guess I need to look at the if's a lot closer. I edited my post with my code to see where I was coming from I guess – Newbee2C Oct 27 '16 at 22:35
  • @PLan I suspect someone is downvoting any answer to this, since they consider the question opinion-based and not deserving an answer. – Barmar Oct 27 '16 at 23:13