I just notice that it's used a lot. It seams more convenient and intuitive to just use a series of if statements. Is there any reason why a switch statement might be better in any case?
A switch generates more efficient compiled code than a series of ifs
Not it doesn't. Most modern compilers would probably produce the same machine code independent of whether ifs or a switch was used.
It seams [sic] more convenient and intuitive to just use a series of if statements.
Actually no, it doesn't. And how is it more "convenient" to write a huge series of if statements in which you'd have to look at every single one every time to see what it actually checks for?
Anyways: Both, switch statements and if-series are often completely unnecessary. Consider this:
int daysAMonth(int month, bool leapYear)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if(leapYear)
{
return 29;
} else {
return 28;
}
default:
return -1;
}
}
Here is an example of where I used an if statement. You could accomplish the exact same thing using switch. My teachers would probably have used a switch. It is easy for me to do it like this, and because I can just copy and past a whole bunch at a time, and change the conditions and arguments using the direction keys really fast.
I'm not saying I think there is something wrong with switch, i just prefer using the ifs. I was just wondering, if people who see my code will think less of me as a programer because I didn't use a switch?
if (key == 'q') alSourcePlay(source[WAV1]);
if (key == 'w') alSourcePlay(source[WAV2]);
if (key == 'e') alSourcePlay(source[WAV3]);
if (key == 'r') alSourcePlay(source[WAV4]);
if (key == 't') alSourcePlay(source[WAV5]);
if (key == 'y') alSourcePlay(source[WAV6]);
if (key == 'u') alSourcePlay(source[WAV7]);
if (key == 'i') alSourcePlay(source[WAV8]);
if (key == 'o') alSourcePlay(source[WAV9]);
if (key == 'p') alSourcePlay(source[WAV10]);
if (key == 'a') alSourcePlay(source[WAV11]);
if (key == 's') alSourcePlay(source[WAV12]);
if (key == 'd') alSourcePlay(source[WAV13]);
if (key == 'f') alSourcePlay(source[WAV14]);
if (key == 'g') alSourcePlay(source[WAV15]);
if (key == 'h') alSourcePlay(source[WAV16]);
if (key == 'j') alSourcePlay(source[WAV17]);
I think it would be better to use a switch there. It makes more sense to me as the programmer. One of the major advantages to using cleaner syntax is that other programmers are more able to read and interpret your code, and therefore will be better able to understand and modify your code if they need something that's slightly different than what you wrote, without having to re-invent the wheel.