Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 3/IF/fr

English · Français · Български · 中文(中国) · 日本語

Tutoriel de Pascal Objet : Structures de contrôle / Branchements conditionnels / Si, sinon

L'instruction IF vous permet de bifurquer selon le résultat d'une opération booléenne. Le format d'une branche unique est :

pascal
if BooleanExpression then
  InstructionSiVrai;

Si l'expression booléenne est évaluée à true, l'instruction est exécutée. Sinon, elle est ignorée.

L'instruction IF accepte une unique instruction. Si vous voulez vous brancher sur une instruction composée, vous devez utiliser un bloc begin-end pour délimiter les instructions :

pascal
if BooleanExpression then
begin
  Instruction1;
  Instruction2
end;

Il y a aussi la sélection à deux voies :

pascal
if BooleanExpression then
  InstructionSiVrai
else
  InstructionSiFaux;

Si l'expression booléenne est évaluée à FALSE, l'instruction suivant le else sera réalisée. Notez que vous ne pouvez pas utiliser le point-virgule après l'instruction précédant le else. Cela amène l'ordinateur à la traiter comme une sélection à branche unique, le laissant à se demander d'où l'autre est venue.

Si vous avez besoin d'une sélection multiple, imbriquez simplement les instructions if :

pascal
if Condition1 then
  Instruction1
else
  if Condition2 then
    Instruction2
  else
    Instruction3;

Soyez prudent avec l'imbrication. Parfois, l'ordinateur ne fera pas ce que vous voulez :

pascal
if Condition1 then
  if Condition2 then
    Instruction2
else
  Instruction1;

Le else correspond toujours au if le plus proche, donc l'ordinateur interprète le bloc de code précédent comme :

pascal
if Condition1 then
  if Condition2 then
    Instruction2
  else
    Instruction1;

Vous pouvez obtenir la même chose avec l'instruction nulle :

pascal
if Condition1 then
  if Condition2 then
    Instruction2
  else
else
  Instruction1;

Ou vous pouvez utiliser un bloc begin-end. Mais la meilleure façon de clarifier le code précédent est de réécrire la condition :

pascal
if not Condition1 then
  Instruction1
else
  if Condition2 then
    Instruction2;

Ces exemples illustrent où l'opérateur not est utile. Si Condition1 était une expression comme : (not(a < b) or (c + 3 > 6)) and g, inverser l'expression serait plus difficile que la préfixer par not.

Aussi, remarquez comment l'indentation transmet la logique du code du programme à un humain, mais le compilateur ignore l'indentation.


From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 3/IF/fr", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.