1144
case PASSED:
printf("Security check passed.\n");
break;
default:
printf("Unknown error (%d), exiting...\n",result);
exit(-1);
}
This label is used because the assumption cannot be made that all possible cases are accounted
for. A good practice is to reserve the default case for error handling.
Example 2:
In the following Java example the method getInterestRate retrieves the interest rate for the number
of points for a mortgage. The number of points is provided within the input parameter and a switch
statement will set the interest rate value to be returned based on the number of points.
Example Language: Java (Bad)
public static final String INTEREST_RATE_AT_ZERO_POINTS = "5.00";
public static final String INTEREST_RATE_AT_ONE_POINTS = "4.75";
public static final String INTEREST_RATE_AT_TWO_POINTS = "4.50";
...
public BigDecimal getInterestRate(int points) {
BigDecimal result = new BigDecimal(INTEREST_RATE_AT_ZERO_POINTS);
switch (points) {
case 0:
result = new BigDecimal(INTEREST_RATE_AT_ZERO_POINTS);
break;
case 1:
result = new BigDecimal(INTEREST_RATE_AT_ONE_POINTS);
break;
case 2:
result = new BigDecimal(INTEREST_RATE_AT_TWO_POINTS);
break;
}
return result;
}
However, this code assumes that the value of the points input parameter will always be 0, 1
or 2 and does not check for other incorrect values passed to the method. This can be easily
accomplished by providing a default label in the switch statement that outputs an error message
indicating an invalid value for the points input parameter and returning a null value.
Example Language: Java (Good)
public static final String INTEREST_RATE_AT_ZERO_POINTS = "5.00";
public static final String INTEREST_RATE_AT_ONE_POINTS = "4.75";
public static final String INTEREST_RATE_AT_TWO_POINTS = "4.50";
...
public BigDecimal getInterestRate(int points) {
BigDecimal result = new BigDecimal(INTEREST_RATE_AT_ZERO_POINTS);
switch (points) {
case 0:
result = new BigDecimal(INTEREST_RATE_AT_ZERO_POINTS);
break;
case 1:
result = new BigDecimal(INTEREST_RATE_AT_ONE_POINTS);
break;
case 2:
result = new BigDecimal(INTEREST_RATE_AT_TWO_POINTS);
break;
default:
System.err.println("Invalid value for points, must be 0, 1 or 2");
System.err.println("Returning null value for interest rate");
result = null;
CWE Version 4.14
CWE-478: Missing Default Case in Multiple Condition Expression
CWE-478: Missing Default Case in Multiple Condition Expression