Log in using your OpenID or your Sol Union log in account.
[Cancel]     

C++ Language Tutorial Page 4
If Statements and Switch Case Statements
Ned Bingham
Previous Index Next
If Statements
     If statements are pretty simple, if the test boolean expression returns true or one, it executes a segment of code. If the test boolean expression returns false, then it goes on to the next iterated if which is an else if and if there is no else if, then else covers everything else.
The syntax is as follows: (If you only have one line of code, you dont need the curly brackets.)
if (boolean expression)
{
	 code goes here... 
}
else if (boolean expression)
{
	 more code... 
}
               .
	       .
	       .
	       .
else if (boolean expression)
{
	 more code... 
} 
else
{
	 even more code... 
}
Switch Case Statements
     Switch case statements are very similar to if statements, except the are a little more specific. Instead of a very general boolean expression, they check whether one variable is equal to many different possibilities. For example, you have an integer a. case 1: is essentially if (a == 1). Here is the syntax.
switch (a)
{
	case 1:
		code goes here...
		break;
	case 2:
                more code goes here...
                break;
	case 3:
                even code goes here...
                break;
	case 4:
                more than even more code goes here...
                break;
	default:
		this handles every other possible case...
		break;
}
     This can be done with any variable type, not just integers. This becomes especially useful when you have to check a ton of values. The keyword break just tells the compiler to break out of the current curly brackets. In this case it would break out of the switch statement. However, you can use that anywhere.