DEV Community

Mirsoli Mirzaahmad õğli
Mirsoli Mirzaahmad õğli

Posted on • Edited on

4 2

Lesson 03 | Conditionals

Types of Conditionals

A conditional in C can be written using if, else-if, else, ternary operators, and switch statements.

if Statements

An if statement tests an expression and executes code based on its truth.

if (x == 3) {
  printf("x is 3!");
}
Enter fullscreen mode Exit fullscreen mode

else-if Statements

An else-if statement tests an expression and must come after an existing if or else-if.

if (x > 3) {
  printf("x is greater than 3");
} else if (x < 3) {
  printf("x is less than 3");
}
Enter fullscreen mode Exit fullscreen mode

else Statements

An else statement is accessed when all preceding if and/or else-if statements return false.

if (x > 3) {
  printf("x is greater than 3");
} else if (x < 3) {
  printf("x is less than 3");
} else {
  printf("x equals 3");
}
Enter fullscreen mode Exit fullscreen mode

Dangling else Statement

A dangling else statement results when it’s ambiguous which conditional the else statement is attached to.

Ternary Operators

A ternary operator is a condensed if-else statement.

min = a < b ? a : b; // This is the same as the if-else below

if (a < b) {
  min = a;
} else {
  min = b;
}
Enter fullscreen mode Exit fullscreen mode

switch Statements

A switch statement is a condensed series of cascading else statements. It tests a value and compares it against multiple cases.

switch (grade) {
  case 9:
    printf("Freshman\n");
    break;
  case 10:
    printf("Sophomore\n");
    break;
  case 11:
    printf("Junior\n");
    break;
  case 12:
    printf("Senior\n");
    break;
  default:
    printf("Invalid\n");
    break;
}
Enter fullscreen mode Exit fullscreen mode

Operators and Conditionals

A conditional in C can use relational operators such as &&, ||, and ! to compare values and test multiple expressions.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay