Jump to content

Conditional (computer programming)

From Simple English Wikipedia, the free encyclopedia
Revision as of 14:04, 25 June 2025 by Wukuendo (talk | changes) (Case, switch, and match statements: Typo)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Conditionals allow blocks of code to give different results based on true or false. The data type that allows for true or false is called a boolean.

If-else or If-then-else

[change | change source]

The if statement is the most basic kind of conditional. It checks that a condition is true, then does an action based on a block of code.

if (condition) { } // code for if the condition is true

By adding an else statement, it will be done, if the condition is false.

if (condition) { } // code for if the condition is true
else { } // code if the condition is false

By adding the else if statement, it is possible to check several conditions in a row, and do actions when the condition it checks for is true.

if (condition) { } // code for if this condition is true
else if (condition) { } // code for if this condition is true
else if (condition) { } // code for if this condition is true
else { } // code for if none of the above conditions happen (false)

Ternary operator (?:)

[change | change source]

A ternary operator is a special operator that is easier to type out and represents conditional statements in several programming languages.

? equals if and : equals else. Instead of if A then B else C, it would be A ? B : C.

int var = (condition) ? X : Y;

Some languages do not use the ternary operator, but do similar, by typing out the if and else statement on the same line.

int var = if (condition) X else Y

Case, switch, and match statements

[change | change source]

Switch statement is the most common term, but it might be called case or match, depending on the language. The switch statement can be used to replace if-else if-else statements.

Pascal: C: V (Vlang):
case someChar of
  'a': actionA;
  'x': actionX;
  'y','z':actionYandZ;
  else actionNoMatch;
end;
switch (someChar) {
  case 'a': actionA; break;
  case 'x': actionX; break;
  case 'y':
  case 'z': actionYandZ; break;
  default: actionNoMatch;
}
match some_char {
  'a' {action_a}
  'x' {action_x}
  'y','z' {action_y_z}
  else {action_no_match}
}