next up previous contents index
Next: Input/Output Up: Conditionals Previous: if() { }   Contents   Index


if/else and ternary operators

There may be times when you want to carry out some statements if a certain condition is met, and then do something else if it's not met. For this you can use an if() { } else { } block:
age = 22;
if (age < 30) {
  printf("You probably don't remember the Beatles, do you?");
}
else {
  printf("You do remember the Beatles, don't you?");
}

For simple if() { } else { } statements it may be possible to use a ternary operator:

  income = 50000;
  tax_rate = (income < 80000) ? 0.3 : 0.5;
subsection switch statemements For more complicated decision trees, the use of a switch block may be convenient:
  int i = 22;
  switch(i) {
  case 15:
    printf("i=%d\n", i);
    break;
  case 22:
    printf("i=%d\n", i);
    break;
  default:
    printf("Default\n");
  }
  return 0;
}
Here, the case statements handle the various possibilities for the expression used in the switch() declaration - the break statements are used here to terminate the switch block. The default statement, which is optional, handles cases that are not handled by the previous case statements.