Need help understanding the " break" in switch function.

0 Bob huginstien · April 5, 2015
Is it necessary  to have a break in this format of a switch code . i know this a generic question. I just want to be sure when and where, to use a break and what will happen if I leave it out. 

ex.

// switch_statement2.cpp
// C2360 expected
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
switch( tolower( *argv[1] ) )
{
// Error. Unreachable declaration.
char szChEntered[] = "Character entered was: ";

case 'a' :
{
// Declaration of szChEntered OK. Local scope.
char szChEntered[] = "Character entered was: ";
cout << szChEntered << "a\n";
}
break;

case 'b' :
// Value of szChEntered undefined.
cout << szChEntered << "b\n";
break;

default:
// Value of szChEntered undefined.
cout << szChEntered << "neither a nor b\n";
break;
}
}


do i need it for all switch functions? is it necessary to use them in while, do-while, and for loops? 

Post a Reply

Replies

Oldest  Newest  Rating
+1 Brian Reed · April 5, 2015
Hello Bob,

Basically you use  break whenever you want to exit out of a Switch or Loop function immediately after a specific condition has tested true. The program will then skip everything else in that function and continue on after the closing brace }

Otherwise,  the execution will continue to run through the function until the end, likely running code for no good reason (although you might have a specific need, say if you wanted to capture all other true conditions). However, without the break statement you may trip on another condition you did not want to occur.

In your example I noticed braces for each case, they should not be there within the switch function. If you can, checkout the C++ Video tutorials, #25 covers the switch statement. One more thing, you don't need a break after the "default:" condition as it is always the last case of the switch function.

Hope this what you needed to know.

Cheers,
Brian



     
0 Bob huginstien · April 5, 2015
Yes this does!  Now I can see how this acts like an if else statement, the break acts like the point in which the statement is true it will exit that switch statement  and if not it goes to another case and breaks there, is that correct?  Thank you very much Brian!:)
0 Brian Reed · April 5, 2015
Yes, you got it!


Cheers,
0 Bob huginstien · April 5, 2015
Cheers! Thank you again kind sir!:)
  • 1

C++

107,325 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator