I have noticed that case and if seem to be very similar in c++. I was wondering what the advantages each has over the other. Thanks.
I have noticed that case and if seem to be very similar in c++. I was wondering what the advantages each has over the other. Thanks.
"Computers aren't intelligent, they only think they are."
**infected by Blizzarddog**
I am a signature virus. Please add me to your signature so that I may multiply
you mean switch and ifelse?
switches are much slower (not noticeably when working with, say, hello world) but a bit easier to read. if-else runs like a burning rocket and is used for asm/microprocessors. Even hello world might come out slow on a 2Mhz processor.
Ph33r the sphericalCUBE ™
A case clause is used in conjunction with a switch statement. One disadvantage of a switch statement compared to if/else statements, is that it only works with ordinal types (int, char).
Most times a switch statement will make your code more readable and well structured.
If usually only use switch statements with constants, enums, etc. eg.
The code above is much simpler than it's if/else equivalent.Code:switch( day ) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: printf( "Working day" ); break; case SATURDAY: case SUNDAY: printf( "No work! Cool" ); break; default: printf( "I dunno!" ); }
Code:if( day == MONDAY || day == TUESDAY || day == WEDNESDAY || day == THURSDAY || day == FRIDAY ) printf( "Working day" ); else if( day == SATURDAY || day == SUNDAY ) printf( "No work! Cool" ); else printf( "I dunno" );
thanks very much for the help
"Computers aren't intelligent, they only think they are."
**infected by Blizzarddog**
I am a signature virus. Please add me to your signature so that I may multiply
>switches are much slower
A switch statement is comparable in speed to a series of if..else if...else statements, to the point where the difference is negligable. If your compiler performs otherwise then it is hopelessly broken.
My best code is written with the delete key.
Isn't a switch quicker than if..then..else if...else because it generates a jump table?
Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie
its compiler specific
Try to help all less knowledgeable than yourself, within
the limits provided by time, complexity and tolerance.
- Nor
Concerning the limit on types, I don't see why you can't allow other types and simply have the compiler convert it to ifelse blocks during the early phases of compilation.