switch case vs if statement

Which is best to use when?

Is a switch case statement just a limited version of the if statement?
Last edited on
Depends.

Switch is better if you need to compare an integral variable to a lot of values (say, five and above). If you need to compare strings or floating point values, if-else-if is better.
But, keep in mind that if has a nesting limit, after which the compiler produces an error. If you need to compare a lot of strings, it's best to put them in a vector, translate the string to an index in the vector, and then use a switch.
Example (actual code):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const char *options[]={
	"--help",
	"-script",
	"-encoding",
	"-music-format",
	"-music-directory",
	"-transparency-method-layer",
	"-transparency-method-anim",
	"-image-cache-size",
	"-debug",
	"-redirect",
	"--version",
	"-implementation",
	"-no-console",
	"-dump-text",
	"-f",
	"-r",
	"-verbosity",
	"-sdebug",
	"-s",
	0
};
long option=-1;
for (long a=0;options[a] && option<0;a++)
	if (!strcmp(argv[argument],options[a]))
		option=a;
switch (option){
	case 0:
		//...
	case 1:
		//...
	//...
};
But, keep in mind that if has a nesting limit, after which the compiler produces an error


Really?I didnt know that?
Topic archived. No new replies allowed.