You are here:

C++/C++ Switch


QUESTION: Hi, these questions are regarding C++ switch statements.

First of all, is there a fundamental difference between using a switch statement and an if-else-if latter? How are 2 correlated and different?

Switch statements can use integers or characters, but I know only the use of integer, can you show me how to use character (like words) as case constants, in the following program?

cout << "Help on:\n";
cout << " 1. if\n";
cout << " 2. switch\n";
cout << "Choose one: \n";
cin >> choice;
cout << "\n";

switch (choice) {
case "1":
cout << "The if:\n\n" << "if (condition) statement;\n"; << "else statement;\n";
case "2":
cout << "The switch:\n\n" << "switch (expression) {\n" << "  case constant: \n" << "    statement sequence \n";
cout << "    break;\n" << "  // ... }\n";
cout << "Selection not found.\n"; }

Follow-up: can integers and characters both be used as case constants?

And some questions regarding other parts of C++:

what is the difference when the increment/decrement operator is before or after the variable? Can you show me an example?

Can you tell me what is the purpose of x=0 in the following program:

int main() {
int x;
for (x=0; x!=123; ) {cout << "Enter a number: ";
cin >> x; }

what does while(ch) means in the following program:

int main() {
unsigned char ch;
ch = 32;
while (ch) {
       cout << ch;
  ch++; }

In general, what does (type) mean in a program? especially when the type is used as the condition.

Last, to create an unsized multidimensional array, one of the size has to be clarified, can this size be any size?
for example, if I need an array of a[5][2], can it be a[5][] and a[][2]?

Thanks so much,

ANSWER: Wow, that's a lot of questions! :)  Ok, here goes:

Switch statements and if/else if blocks perform basically the same task (with some trickery allowed in switch statements that isn't easily done with if/else if).  However, switch statements have the potential to be considerably more optimized by the compiler than an if/else if block.  Generally, it's better form to use switch statements than if/else if.  

However, there are circumstances that simply won't work in a switch statements, such as using a string as the case.  A switch statement works only with a numeric value as the case.  So, if you have a string value that you wish to use as a case value for a switch statement, then you need to somehow convert that string value into a numeric value.

Basically, if you can use a switch statement, you probably should.  They tend to be faster than a corresponding if/else if block, and even in the worst case should be exactly equivalent to an if/else if block.

I mentioned earlier that switch statements allowed some trickery that isn't easily done in an if/else if block.  Specifically what I am referring to is fall through.  As you are aware, in a switch statement, you terminate case blocks with a break command.  If you do not terminate a block with a break, then the code will actually continue on to the next case within the switch statement.  Generally that is undesired, however, it is sometimes entirely desirable.  This allows for easy grouping of blocks with the same output or for complex behavior such as special cases that also share behaviors with other cases.  A good example of this is shown in Wikipedia's article on switch statements:

Now, in your specific switch statement example, you could interpret the user's input as a character instead of a string by simply taking the first character of the input string, either by just dereferencing the pointer or using the [] operator.  Example:

switch (*choice)
case '1':
cout << "The if:\n\n" << "if (condition) statement;\n"; << "else statement;\n";
case '2':
cout << "The switch:\n\n" << "switch (expression) {\n" << "  case constant: \n" << "    statement sequence \n";
cout << "    break;\n" << "  // ... }\n";
cout << "Selection not found.\n"; }

For your followup, as demonstrated above, yes both integers and characters may be used as case constants.  However, I think you may be confusing character and string (or character array).  A character string is actually just a pointer to a block of memory which contains a number of contiguous characters forming a string.  The characters themselves are just a numeric value which reference a standardized symbol table.  For example, the character 'a' (specifically the lower-case a) has a value of 97.  This means, when you use 'a' as a case in a switch statement, it's the same as using the number 97 as a case in a switch statement.

On to the other questions!

The difference of ++ and -- being before or after a variable is a subtle difference, but a very important one.  When the operator occurs before a variable, it is called a prefix operator.  When it is after a variable, it is called a postfix operator.  Prefix operators execute before anything else, whereas postfix operators execute after everything else.  Let's examine this with an example:

   int blah = 0;
   cout << ++blah << endl;
   cout << blah++ << endl;

This code would print:


You see how the prefix operator incremented the variable blah before it was used, taking its value from 0 to 1.  Then, the postfix operator let the line of code execute before incrementing the number.  In the end, the value in the variable "blah" is 2, though it only ever printed out a 1.

One interesting thing to note about the prefix versus postfix operators is that the prefix operator is actually faster than the postfix operator.  So, if you ever have a choice of which one to use (which is less often than you might thing), always use the prefix operator.  If you like, I can go into detail on why the prefix is faster than the postfix (it isn't a big difference, but sometimes a lot of small fixes make all the difference in the world).

Next, in the code you've given, the x=0 initializes the x variable to 0 before beginning the loop.  If you do not initialize a variable before you use it, you have absolutely no idea what value it contains.  Always, always, always, ALWAYS initialize variables before you use them.

In the next small function you've given, the while(ch) sets up a while loop.  The loop condition in this case is simply "ch."  Basically while the ch variable is non-zero (true), the loop will execute.  Once the ch variable is 0, the loop will stop.  In this particular loop, it's relying on variable wrap-around, so once the maximum value for an unsigned char is reached (255), the variable will wrap around to 0 and the while condition will evaluate to false (since 0 is false).  This function prints out every character from value 32 to 255, the generally accepted set of visual characters in ASCII (the first 32 characters, 0 - 31, are control characters with various meanings/uses).

I'm not sure what your next question means (about (type)).  Could you clarify?

Finally, you can only declare it as a[][2] or a[5][2].  Not sure why, that's just how it is.  For whatever reason, a[5][] doesn't work.  It generates a compile error.

---------- FOLLOW-UP ----------

QUESTION: sorry for the loads of question, the question you're asking about is

why switch statements need a variable when all other control statement go with a condition,
like this

switch (var) {//.......};

By the way, I also have some questions about pointers, can you help me?
I understand that pointer is an object that contains the address of a variable that contain a value,
1) what is the value of the pointer itself? the same as that of the pointed variable?
2) once the var is placed in the pointer, does it have the same address as that of the pointer?
3) can a pointer have two or more vars?
4) are the type of the pointer and the pointed object the same?
5) can you explain the use of the 2 pointer operators?


Essentially, the best way I can describe a switch statement is that the case statements are the conditions, and the switch statement declares where the condition exists.  I don't know if that exactly makes sense, but I'll try to demonstrate.

In a simple example where we have something like:

   switch (myIntegerVar)
       case 0:
         // do something
       case 1:
         // do something else

This is equivalent to:

   if (myIntegerVar == 0)
       // do something
   else if (myIntegerVar == 1)
       // do something else

So you can see that a condition statement still exists within a switch statement, it's just reordered a bit.  It really just boils down to a syntactical decision made by the developers of the language.  A switch statement is, I think, a rather intuitive, logical way of diagramming something and it's been turned into a functional method of programming by the creators of the language.

If this isn't clear, please let me know and I can try to explain it differently.  It's honestly something I've never really considered or given much thought to. :)  Moving on.

Pointers.  I love pointers.  They're incredibly handy and there are all sorts of fun little tricks you can do with them.

1. The value of the pointer is the memory address at which its data resides.  When you allocate a piece of memory, it returns an address, and that address is what gets stored into the pointer.  So, if you allocate something and it ends up at the address 0x10001000, then the value of the pointer would be 0x10001000.

2. Writing into the address that the pointer points to does not change the pointer in any way whatsoever.  Also, do not confuse the address of the pointer with the address that the pointer points to.  The pointer is, itself, a variable, and so has its own address.  This can be confusing, and often times the concept of a double pointer, or pointer to a pointer, is ignored completely when first discussing pointers.  However, it is an important distinction to make and double pointers are immensely useful.

3. Sort of.  I'll clarify by discussing arrays.  Something that generally isn't taught, at least initially, is that an array is a pointer.  When you declare an array, what you are doing is telling the system to set aside a single, contiguous block of memory to contain some number of like objects.  The array variable itself is actually nothing more than a pointer to the block of memory which is set aside.  Let's look at the following code:

   int myArray[5];

In this code, we're telling the system that we need a single block of memory with a size of sizeof(int) * 5, which in most OSes these days, is 20 bytes, since an integer is typically 4 bytes.  The myArray variable is actually just a pointer which points to the first of these integers.  When you index into the array with the [] operator, you are, in fact, telling the system that you want to move X number of blocks forward from the starting address of the pointer, where X is the number inside the [] and a block is sizeof(int).  The following code is equivalent to the above example:

   int myArray* = new int[5];

In both cases, myArray is really nothing but a pointer, and it points to an integer.  So yes, if you have allocated an array, a pointer may point to more than one var.

4. Well, a pointer is a pointer.  That sounds rather silly, but it is important to understand that when you declare a pointer of *any* type, the pointer itself is always a pointer.  As I mentioned above, in a 32-bit operating system, that means that a pointer is a 32-bit value.  So a char* is actually larger than a char, since a char is an 8-bit value.

However, the type of a pointer is very important when it comes to manipulating the pointer.  If we declare an integer array, then every time we increment from the starting address, it increments by the size of an integer.  If we declare a character array, then every time we increment from the starting address, it increments by the size of a character.

The type of a pointer tells the system how big the item it's pointing to is, so that information can be used to move the memory address with various operations.  This is a very important concept to understand and can lead to some pretty nasty, hard-to-track bugs if you misuse pointer arithmetic.

5. I'm not entirely certain of the question here, but I think I know which operators to which you are referring.  I'm assuming that you are referring to the * and & operators.  I assure you, though, there are many more than 2 operators that may be used on a pointer. :)

The * operator is used to dereference a pointer.  Because a pointer is just a variable storing a memory address, and the pointer itself may be changed to point to a new memory address, any time you wish to access the data pointed to by a pointer, you need to explicitly request that data.  This is accomplished with the * operator.  It tells the system to resolve the memory address and allows access and manipulation of the data stored at that address.

The & operator is basically the exact opposite of the * operator.  Where * takes an address and returns the data, & takes data and returns the address.  So, if you have declared a variable and you wish to create a pointer to that variable, then you can use the & operator to retrieve the variable's address:

   int myIntVar = 0;
   int* myIntPtr = &myIntVar;

Ok, I think that covers everything.  If I misinterpreted a question or otherwise improperly answered a question, please feel free to ask me to clarify.  I'm always happy to help.


All Answers

Answers by Expert:

Ask Experts


Joseph Moore


I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.


I've been writing C++ code for 12 years, both on my own in my spare time and professionally.


Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 All rights reserved.