Menu Close


C: Decision statement

First control statement we learn in C must be “if” statement. This is very simple but also powerful. It is used in most computer languages to enable or disable execution of next statement depending on a logical deduction named condition.

Conditional Expression

A condition is a logical expression or value. In C logical expressions can have as result two values: { 0 = False, 1 = True }. Any value = 0 is considered False. Any value ≠ 0 is considered True.

In practice most common logical expressions are comparison between two variables, constants or literals using relation operators. In the next table you can analyze these operators and two examples: Positive and Negative

Relation Operators:

OperatorDescriptionPositive = 1Negative = 0
==Equal1 == 1 1 == 0
>=Greater than or equal to1 >= 01 >= 2
<=Less than or equal to1 <= 11 <= 0
>Greater than2 > 15 > 5 + 1
<Less than0 < 11 < 0

Logical Operators:

Logical operators can be used in C with any numeric value. There is no Boolean reserved type. So any numeric literal = 0, = 1 or numeric value >=0 will do. There is no other type checking so you may do it all wrong but C will not worn you about type mismatch.

There are 3 logical operators:

  • Negation = “!”,
  • Logic AND = “&&”
  • Logic OR = “||”

Table of truth:

Values: A/BDescription ->NOT AA AND BA OR B
AB !A  A && BA || B 

IF Statement

In the next example we use “if” keyword two times. First time will create a “branch” that print “this is expected”. This branch is executed since x = 0. Second time we create a branch that will never execute since is not > 0. So the string “this is unexpected” will never be printed:

Syntax description:

If statement can be used in more than one way. You can create two or more branches using “else” keyword. Also the brackets { } are not necessary for a single statement, but instead you use “;”.

Nested Statements

Not only “if” statement but all block statements can be nested. That means inside of a block statement you can create another block statement. We advice developers to reduce the number of nested levels as much as possible.


Read Next: Selection statement