Could someone explain switches to me in a way I can understand. It's not to clear to me how the book I am reading is explaining it. Thanks in advance.
-andy
Printable View
Could someone explain switches to me in a way I can understand. It's not to clear to me how the book I am reading is explaining it. Thanks in advance.
-andy
understand. Now, are switch statements important in C++? Anyone use them in their projects? Thx.
-andy
yes it's useful when you wnt to test for a lot of integral values. heck lot of cleaner and easier to type/write than a bunch of else ifs, and you can leave out "break" to do some special things, a boring example would be to have the same code for two cases. eg:Quote:
Originally posted by andy3109
understand. Now, are switch statements important in C++? Anyone use them in their projects? Thx.
-andy
case 1:
foo();
break;
case 3:
case 4:
bar();
break;
you will use it sometime.
Switches are much faster then chained if-elses.
can you do cases that make perform a function if x<30 or something like that?
-andy
No, a switch only can only compare the variable to a single number or a single letter, not an expression. Use an if statement for that.
please dont mine my late post. i am new to this form.
the reason we have swites is cause c technically does not have something called an "else if" it rather has something else called "if else".
the following...
if (x=1)
printf("1");
else if (x=2)
printf("2");
else
printf("3");
is the same thing as
if (x=1)
{
printf("1");
}
else
{
if (x=2)
printf("2");
else
printf("3");
}
wich is the same as...
if (x=1)
printf("1");
else
if (x=2)
printf("2");
else
printf("3");
wich is the same as...
if (x=1)
printf("1");
else if (x=2)
printf("2");
else
printf("3");
now do you see how the else if come about? the switch statment does the same thing more efficiantly from a low level perspective.
good example of a switch:
[code]
int days=0;
cout << "Enter the number of days: ";
cin >> days;
cout << "On the " << days << " day of Christmas my true love sent to me: " << endl;
switch(days)
{
case 12:
cout << "12 Drummers Drumming" << endl;
case 11:
cout << "Eleven Pipers Piping" << endl;
case 10:
cout << "Ten Lords a Leaping" << endl;
case 9:
cout << "Nine Ladies Dancing" << endl;
case 8:
cout << "Eight Maids a Milking" << endl;
case 7:
cout << "Seven Swans a Swimming" << endl;
case 6:
cout << "Six Geese a Laying" << endl;
case 5:
cout << "Five Golden Rings" << endl;
case 4:
cout << "Four Calling Birds" << endl;
case 3:
cout << "Three French Hens" << endl;
case 2:
cout << "Two Turtle Doves" << endl;
case 1:
cout << "and a Partridge in a Pear Tree" << endl;
}