Considera i due diagrammi di flusso e le corrispondenti codifiche

C, C++, Java, …
if(A > 0)
{
if(B > 0)
{
istr11;
istr12;
}
else
{
istr21;
istr22;
}
}
if(A > 0)
{
if(B > 0)
{
istr11;
istr12;
}
}
else
{
istr21;
istr22;
}
if(A > 0)
if(B > 0)
{
istr11;
istr12;
}
else
{
istr21;
istr22;
}
CODICE ERRATO!
Pascal
If A > 0 Then
Begin
If B > 0 Then
Begin
Istr11;
Istr12;
End
Else
Begin
Istr21;
Istr22;
End;
End;
If A > 0 Then
Begin
If B > 0 Then
Begin
Istr11;
Istr12;
End
End
Else
Begin
Istr21;
Istr22;
End;
If A > 0 Then
If B > 0 Then
Begin
Istr11;
Istr12;
End
Else
Begin
Istr21;
Istr22;
End;
CODICE ERRATO!
Python
if A > 0:
if B > 0:
Istr11
Istr12
else:
Istr21
Istr22
if A > 0:
if B > 0:
Istr11
Istr12
else:
Istr21
Istr22
Visual Basic
If(A > 0) Then
If(B > 0) Then
Istr11
Istr12
Else
Istr21
Istr22
End If
End If
If(A > 0) Then
If(B > 0) Then
Istr11
Istr12
...
End If
Else
Istr21
Istr22
...
End If
Un programmatore inesperto potrebbe produrre il codice nell’ultima colonna per il secondo diagramma di flusso.
Purtroppo il compilatore lo interpreterà come corrispondente al primo diagramma…
- il compilatore non prende in considerazione l’indentazione ma associa correttamente l’Else all’ultimo If rimasto aperto
- il ramo Else si sposta da sinistra verso destra, ciondola.
Osserva
- In Basic non si può sbagliare perché l’etichetta END IF è sempre presente e differenzia i due casi.
- In Python non si può sbagliare perché l’indentazione è sempre presente e differenzia i due casi.
- In C... e Pascal si risolve l’ambiguità utilizzando le etichette di apertura e chiusura dei blocchi.
Il programmatore alle prime armi, per evitare di incorrere nell’errore dell’else ciondolante, dovrebbe utilizzare sempre le etichette di inizio e fine blocco