Language: EN

programacion-condicional-if-else

The IF-ELSE conditional

The conditional IF-ELSE is an evolution of the simple IF, which allows us to add code to execute when the condition is false.

Colloquially, the conditional IF-ELSE means,

If this happens 🡆 do this

If not 🡆 do this other thing

Which, in code format, would look something like this,

if(condition)
{
	// actions to execute if condition is true
}
else
{
	// actions to execute if condition is false
}

And in the form of a flowchart, it would look something like this

programacion-if-else

IF-ELSE Diagram

Examples of IF-ELSE conditionals in different languages

Let’s see an example of the IF-ELSE conditional. In this example, let’s assume we have to evaluate the exam grade.

  • If it is greater than 5, the student has passed 🟢
  • If it is less than 5, the student has failed 🔴

In the case of C++, C#, Java, Kotlin, or JavaScript, this IF-ELSE conditional looks like this,

if (exam_grade >= 5)
{
	// show message 'Congratulations! You have passed' 🟢
}
else
{
	// show message 'Sorry, you have failed' 🔴
}

In PHP, an IF conditional is identical, with the peculiarity that variables are preceded by ’$’

if ($exam_grade >= 5) 
{
    // show message 'Congratulations! You have passed' 🟢
}
else 
{
   // show message 'Sorry, you have failed' 🔴
}

On the other hand, Python has the following form

if exam_grade >= 5:
    # show message 'Congratulations! You have passed' 🟢
else:
	# show message 'Sorry, you have failed' 🔴

And in VB, which has a somewhat longer syntax because it aims for a natural language

If exam_grade >= 5 Then
	' show message 'Congratulations! You have passed' 🟢
Else
	' show message 'Sorry, you have failed' 🔴
End If

To give a somewhat “strange” example, in SQL a conditional has the following form

CASE
	WHEN @exam_grade >= 5 THEN 'Congratulations! You have passed 🟢'
	ELSE 'Sorry, you have failed 🔴'
END AS message;

That is to say, basically the structure of an IF conditional is identical in most languages, beyond some peculiarities of syntax of each of them.

Internal Functioning Advanced

Internally, the control flow of the program is similar to that of the IF block. The control flow encounters a conditional jump, which evaluates a certain condition.

If the condition is true, the flow continues with the instructions of the IF body. If it is false, it jumps to the body of the ELSE.

programacion-if-else-saltos

Conditional jump generated by the IF-ELSE

In the case of the IF body, at the end of it, there is a GO-TO jump to the end of the ELSE body. In the end, both reach the same execution point.

In this way, we have created a code bifurcation, where certain instructions are executed depending on the conditional jump. Finally, both come together, and the program continues.